﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using Microsoft.VisualBasic;
using System.Collections;
using System.Drawing;
using System.Net;
using System.Globalization;
using System.Collections.Generic;

using CMN.Entity;
using System.Configuration;
using Microsoft.Win32;
using System.Data;
using ICSharpCode.SharpZipLib.GZip;
namespace CMN.Common
{

	/// <summary>
	/// 工具类
	/// </summary>
    public class Utils
    {

        public static void Redirect404()
        {
            if(System.Web.HttpContext.Current!=null){
                System.Web.HttpContext.Current.Response.Redirect("/404.aspx");
                System.Web.HttpContext.Current.Response.End();
            }
            
        }
        #region 分页数量
        /// <summary>
        /// 分页数量
        /// </summary>
        public static int PageSize = 10;
        #endregion 

        #region 获取汉字全拼

        private static int[] pyValue = new int[]
    {
    -20319,-20317,-20304,-20295,-20292,-20283,-20265,-20257,-20242,-20230,-20051,-20036,
    -20032,-20026,-20002,-19990,-19986,-19982,-19976,-19805,-19784,-19775,-19774,-19763,
    -19756,-19751,-19746,-19741,-19739,-19728,-19725,-19715,-19540,-19531,-19525,-19515,
    -19500,-19484,-19479,-19467,-19289,-19288,-19281,-19275,-19270,-19263,-19261,-19249,
    -19243,-19242,-19238,-19235,-19227,-19224,-19218,-19212,-19038,-19023,-19018,-19006,
    -19003,-18996,-18977,-18961,-18952,-18783,-18774,-18773,-18763,-18756,-18741,-18735,
    -18731,-18722,-18710,-18697,-18696,-18526,-18518,-18501,-18490,-18478,-18463,-18448,
    -18447,-18446,-18239,-18237,-18231,-18220,-18211,-18201,-18184,-18183, -18181,-18012,
    -17997,-17988,-17970,-17964,-17961,-17950,-17947,-17931,-17928,-17922,-17759,-17752,
    -17733,-17730,-17721,-17703,-17701,-17697,-17692,-17683,-17676,-17496,-17487,-17482,
    -17468,-17454,-17433,-17427,-17417,-17202,-17185,-16983,-16970,-16942,-16915,-16733,
    -16708,-16706,-16689,-16664,-16657,-16647,-16474,-16470,-16465,-16459,-16452,-16448,
    -16433,-16429,-16427,-16423,-16419,-16412,-16407,-16403,-16401,-16393,-16220,-16216,
    -16212,-16205,-16202,-16187,-16180,-16171,-16169,-16158,-16155,-15959,-15958,-15944,
    -15933,-15920,-15915,-15903,-15889,-15878,-15707,-15701,-15681,-15667,-15661,-15659,
    -15652,-15640,-15631,-15625,-15454,-15448,-15436,-15435,-15419,-15416,-15408,-15394,
    -15385,-15377,-15375,-15369,-15363,-15362,-15183,-15180,-15165,-15158,-15153,-15150,
    -15149,-15144,-15143,-15141,-15140,-15139,-15128,-15121,-15119,-15117,-15110,-15109,
    -14941,-14937,-14933,-14930,-14929,-14928,-14926,-14922,-14921,-14914,-14908,-14902,
    -14894,-14889,-14882,-14873,-14871,-14857,-14678,-14674,-14670,-14668,-14663,-14654,
    -14645,-14630,-14594,-14429,-14407,-14399,-14384,-14379,-14368,-14355,-14353,-14345,
    -14170,-14159,-14151,-14149,-14145,-14140,-14137,-14135,-14125,-14123,-14122,-14112,
    -14109,-14099,-14097,-14094,-14092,-14090,-14087,-14083,-13917,-13914,-13910,-13907,
    -13906,-13905,-13896,-13894,-13878,-13870,-13859,-13847,-13831,-13658,-13611,-13601,
    -13406,-13404,-13400,-13398,-13395,-13391,-13387,-13383,-13367,-13359,-13356,-13343,
    -13340,-13329,-13326,-13318,-13147,-13138,-13120,-13107,-13096,-13095,-13091,-13076,
    -13068,-13063,-13060,-12888,-12875,-12871,-12860,-12858,-12852,-12849,-12838,-12831,
    -12829,-12812,-12802,-12607,-12597,-12594,-12585,-12556,-12359,-12346,-12320,-12300,
    -12120,-12099,-12089,-12074,-12067,-12058,-12039,-11867,-11861,-11847,-11831,-11798,
    -11781,-11604,-11589,-11536,-11358,-11340,-11339,-11324,-11303,-11097,-11077,-11067,
    -11055,-11052,-11045,-11041,-11038,-11024,-11020,-11019,-11018,-11014,-10838,-10832,
    -10815,-10800,-10790,-10780,-10764,-10587,-10544,-10533,-10519,-10331,-10329,-10328,
    -10322,-10315,-10309,-10307,-10296,-10281,-10274,-10270,-10262,-10260,-10256,-10254
    };

        private static string[] pyName = new string[]
    {
    "A","Ai","An","Ang","Ao","Ba","Bai","Ban","Bang","Bao","Bei","Ben",
    "Beng","Bi","Bian","Biao","Bie","Bin","Bing","Bo","Bu","Ba","Cai","Can",
    "Cang","Cao","Ce","Ceng","Cha","Chai","Chan","Chang","Chao","Che","Chen","Cheng",
    "Chi","Chong","Chou","Chu","Chuai","Chuan","Chuang","Chui","Chun","Chuo","Ci","Cong",
    "Cou","Cu","Cuan","Cui","Cun","Cuo","Da","Dai","Dan","Dang","Dao","De",
    "Deng","Di","Dian","Diao","Die","Ding","Diu","Dong","Dou","Du","Duan","Dui",
    "Dun","Duo","E","En","Er","Fa","Fan","Fang","Fei","Fen","Feng","Fo",
    "Fou","Fu","Ga","Gai","Gan","Gang","Gao","Ge","Gei","Gen","Geng","Gong",
    "Gou","Gu","Gua","Guai","Guan","Guang","Gui","Gun","Guo","Ha","Hai","Han",
    "Hang","Hao","He","Hei","Hen","Heng","Hong","Hou","Hu","Hua","Huai","Huan",
    "Huang","Hui","Hun","Huo","Ji","Jia","Jian","Jiang","Jiao","Jie","Jin","Jing",
    "Jiong","Jiu","Ju","Juan","Jue","Jun","Ka","Kai","Kan","Kang","Kao","Ke",
    "Ken","Keng","Kong","Kou","Ku","Kua","Kuai","Kuan","Kuang","Kui","Kun","Kuo",
    "La","Lai","Lan","Lang","Lao","Le","Lei","Leng","Li","Lia","Lian","Liang",
    "Liao","Lie","Lin","Ling","Liu","Long","Lou","Lu","Lv","Luan","Lue","Lun",
    "Luo","Ma","Mai","Man","Mang","Mao","Me","Mei","Men","Meng","Mi","Mian",
    "Miao","Mie","Min","Ming","Miu","Mo","Mou","Mu","Na","Nai","Nan","Nang",
    "Nao","Ne","Nei","Nen","Neng","Ni","Nian","Niang","Niao","Nie","Nin","Ning",
    "Niu","Nong","Nu","Nv","Nuan","Nue","Nuo","O","Ou","Pa","Pai","Pan",
    "Pang","Pao","Pei","Pen","Peng","Pi","Pian","Piao","Pie","Pin","Ping","Po",
    "Pu","Qi","Qia","Qian","Qiang","Qiao","Qie","Qin","Qing","Qiong","Qiu","Qu",
    "Quan","Que","Qun","Ran","Rang","Rao","Re","Ren","Reng","Ri","Rong","Rou",
    "Ru","Ruan","Rui","Run","Ruo","Sa","Sai","San","Sang","Sao","Se","Sen",
    "Seng","Sha","Shai","Shan","Shang","Shao","She","Shen","Sheng","Shi","Shou","Shu",
    "Shua","Shuai","Shuan","Shuang","Shui","Shun","Shuo","Si","Song","Sou","Su","Suan",
    "Sui","Sun","Suo","Ta","Tai","Tan","Tang","Tao","Te","Teng","Ti","Tian",
    "Tiao","Tie","Ting","Tong","Tou","Tu","Tuan","Tui","Tun","Tuo","Wa","Wai",
    "Wan","Wang","Wei","Wen","Weng","Wo","Wu","Xi","Xia","Xian","Xiang","Xiao",
    "Xie","Xin","Xing","Xiong","Xiu","Xu","Xuan","Xue","Xun","Ya","Yan","Yang",
    "Yao","Ye","Yi","Yin","Ying","Yo","Yong","You","Yu","Yuan","Yue","Yun",
    "Za", "Zai","Zan","Zang","Zao","Ze","Zei","Zen","Zeng","Zha","Zhai","Zhan",
    "Zhang","Zhao","Zhe","Zhen","Zheng","Zhi","Zhong","Zhou","Zhu","Zhua","Zhuai","Zhuan",
    "Zhuang","Zhui","Zhun","Zhuo","Zi","Zong","Zou","Zu","Zuan","Zui","Zun","Zuo"
    };

        /// <summary>
        /// 把汉字转换成拼音(全拼)
        /// </summary>
        /// <param name="hzString">汉字字符串</param>
        /// <returns>转换后的拼音(全拼)字符串</returns>
        public static string ChineseToQuanPin(string hzString)
        {
            // 匹配中文字符
            Regex regex = new Regex("^[\u4e00-\u9fa5]$");
            byte[] array = new byte[2];
            string pyString = "";
            int chrAsc = 0;
            int i1 = 0;
            int i2 = 0;
            char[] noWChar = hzString.ToCharArray();

            for (int j = 0; j < noWChar.Length; j++)
            {
                // 中文字符
                if (regex.IsMatch(noWChar[j].ToString()))
                {
                    array = System.Text.Encoding.Default.GetBytes(noWChar[j].ToString());
                    i1 = (short)(array[0]);
                    i2 = (short)(array[1]);
                    chrAsc = i1 * 256 + i2 - 65536;
                    if (chrAsc > 0 && chrAsc < 160)
                    {
                        pyString += noWChar[j];
                    }
                    else
                    {
                        // 修正部分文字
                        if (chrAsc == -9254)  // 修正“圳”字
                            pyString += "Zhen";
                        else
                        {
                            for (int i = (pyValue.Length - 1); i >= 0; i--)
                            {
                                if (pyValue[i] <= chrAsc)
                                {
                                    pyString += pyName[i];
                                    break;
                                }
                            }
                        }
                    }
                }
                // 非中文字符
                else
                {
                    pyString += noWChar[j].ToString();
                }
            }
            return pyString;
        }


        /// <summary> 
        /// 在指定的字符串列表CnStr中检索符合拼音索引字符串 
        /// </summary> 
        /// <param name="CnStr">汉字字符串</param> 
        /// <returns>相对应的汉语拼音首字母串</returns> 
        public static string GetSpellCode(string CnStr)
        {
            string strTemp = "";
            int iLen = CnStr.Length;
            int i = 0;

            for (i = 0; i <= iLen - 1; i++)
            {
                strTemp += GetCharSpellCode(CnStr.Substring(i, 1));
            }

            return strTemp;
        }


        /// <summary> 
        /// 得到一个汉字的拼音第一个字母，如果是一个英文字母则直接返回大写字母 
        /// </summary> 
        /// <param name="CnChar">单个汉字</param> 
        /// <returns>单个大写字母</returns> 
        private static string GetCharSpellCode(string CnChar)
        {
            long iCnChar;

            byte[] ZW = System.Text.Encoding.Default.GetBytes(CnChar);

            //如果是字母，则直接返回 
            if (ZW.Length == 1)
            {
                return CnChar.ToUpper();
            }
            else
            {
                // get the array of byte from the single char 
                int i1 = (short)(ZW[0]);
                int i2 = (short)(ZW[1]);
                iCnChar = i1 * 256 + i2;
            }

            //expresstion 
            //table of the constant list 
            // 'A'; //45217..45252 
            // 'B'; //45253..45760 
            // 'C'; //45761..46317 
            // 'D'; //46318..46825 
            // 'E'; //46826..47009 
            // 'F'; //47010..47296 
            // 'G'; //47297..47613 

            // 'H'; //47614..48118 
            // 'J'; //48119..49061 
            // 'K'; //49062..49323 
            // 'L'; //49324..49895 
            // 'M'; //49896..50370 
            // 'N'; //50371..50613 
            // 'O'; //50614..50621 
            // 'P'; //50622..50905 
            // 'Q'; //50906..51386 

            // 'R'; //51387..51445 
            // 'S'; //51446..52217 
            // 'T'; //52218..52697 
            //没有U,V 
            // 'W'; //52698..52979 
            // 'X'; //52980..53640 
            // 'Y'; //53689..54480 
            // 'Z'; //54481..55289 

            // iCnChar match the constant 
            if ((iCnChar >= 45217) && (iCnChar <= 45252))
            {
                return "A";
            }
            else if ((iCnChar >= 45253) && (iCnChar <= 45760))
            {
                return "B";
            }
            else if ((iCnChar >= 45761) && (iCnChar <= 46317))
            {
                return "C";
            }
            else if ((iCnChar >= 46318) && (iCnChar <= 46825))
            {
                return "D";
            }
            else if ((iCnChar >= 46826) && (iCnChar <= 47009))
            {
                return "E";
            }
            else if ((iCnChar >= 47010) && (iCnChar <= 47296))
            {
                return "F";
            }
            else if ((iCnChar >= 47297) && (iCnChar <= 47613))
            {
                return "G";
            }
            else if ((iCnChar >= 47614) && (iCnChar <= 48118))
            {
                return "H";
            }
            else if ((iCnChar >= 48119) && (iCnChar <= 49061))
            {
                return "J";
            }
            else if ((iCnChar >= 49062) && (iCnChar <= 49323))
            {
                return "K";
            }
            else if ((iCnChar >= 49324) && (iCnChar <= 49895))
            {
                return "L";
            }
            else if ((iCnChar >= 49896) && (iCnChar <= 50370))
            {
                return "M";
            }

            else if ((iCnChar >= 50371) && (iCnChar <= 50613))
            {
                return "N";
            }
            else if ((iCnChar >= 50614) && (iCnChar <= 50621))
            {
                return "O";
            }
            else if ((iCnChar >= 50622) && (iCnChar <= 50905))
            {
                return "P";
            }
            else if ((iCnChar >= 50906) && (iCnChar <= 51386))
            {
                return "Q";
            }
            else if ((iCnChar >= 51387) && (iCnChar <= 51445))
            {
                return "R";
            }
            else if ((iCnChar >= 51446) && (iCnChar <= 52217))
            {
                return "S";
            }
            else if ((iCnChar >= 52218) && (iCnChar <= 52697))
            {
                return "T";
            }
            else if ((iCnChar >= 52698) && (iCnChar <= 52979))
            {
                return "W";
            }
            else if ((iCnChar >= 52980) && (iCnChar <= 53640))
            {
                return "X";
            }
            else if ((iCnChar >= 53689) && (iCnChar <= 54480))
            {
                return "Y";
            }
            else if ((iCnChar >= 54481) && (iCnChar <= 55289))
            {
                return "Z";
            }
            else return (CnChar);
        }

        #endregion

        #region 采集

        /// <summary>
        /// 获取内容中第一个图片地址
        /// </summary>
        /// <param name="strContent">详细内容</param>
        /// <returns></returns>
        public static string GetFirstImg(string strContent)
        {
            string strRetrun = string.Empty;
            Common.RegExpression.ImageRegExpression imgRg = new Common.RegExpression.ImageRegExpression();
            Common.RegExpression.RegContext regContent = new CMN.Common.RegExpression.RegContext(strContent, 'M', "");
            imgRg.Evaluate(regContent);
            string a_url = string.Empty;
            string TempStr = string.Empty;
            string TitleImg = string.Empty;
            foreach (string strmatch in regContent.Matches)
            {

                if (TempStr != string.Empty)
                    TempStr += "$Array$" + strmatch.ToString();
                else
                    TempStr = strmatch.ToString();

            }

            string[] TempArr = TempStr.Split(new string[] { "$Array$" }, StringSplitOptions.None);
            TempStr = string.Empty;
            Regex imgReg = new Regex(@"src\s*=\s*.+?\.(gif|jpg|bmp|jpeg|psd|png)", RegexOptions.IgnoreCase);
            for (int i = 0; i < TempArr.Length; i++)
            {
                MatchCollection matches = imgReg.Matches(TempArr[i]);
                foreach (Match match in matches)
                {
                    if (!match.ToString().StartsWith("http"))
                    {
                        strRetrun = match.ToString();
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(strRetrun))
                {
                    if (strRetrun.Length > 0)
                    {
                        imgReg = new Regex(@"src\s*=\s*", RegexOptions.IgnoreCase);
                        strRetrun = imgReg.Replace(strRetrun, "");
                    }

                    strRetrun = strRetrun.Replace("\"", "");
                    strRetrun = strRetrun.Replace("'", "");
                    strRetrun = strRetrun.Replace(" ", "");
                    break;
                }
            }
            return strRetrun;

        }

 

        /// <summary>
        /// 网页相对路径转全路径
        /// </summary>
        /// <param name="Sourcepath">源码地址</param>
        /// <param name="Relativepath">相对地址</param>
        /// <returns></returns>
        public static string GetAbsolutePath(string Sourcepath, string Relativepath)
        {
            Sourcepath = Sourcepath.ToLower();
            if (Relativepath.IndexOf("http://") > -1)
            {
                return Relativepath;
            }
            else if (Relativepath.Substring(0, 2) == "//")
            {
                //string[] sd = Sourcepath.Replace("http://", "").Split('/');
                return "http:" + Relativepath;
            }
            else if (Relativepath.Substring(0, 1) == "/")
            {
                string[] sd = Sourcepath.Replace("http://", "").Split('/');
                return "http://" + sd[0] + Relativepath;
            }
            else
            {
                string[] sd = Relativepath.Split('/');
                if (sd[0] != "..")
                {
                    if ((sd[0].IndexOf(".net") > -1) || (sd[0].IndexOf(".cn") > -1) || (sd[0].IndexOf(".org") > -1) || (sd[0].IndexOf(".com") > -1) || (sd[0].IndexOf(".cc") > -1))
                    {
                        return "http://" + Relativepath;
                    }
                    else
                    {

                        string[] sd1 = Sourcepath.Replace("http://", "").Split('/');
                        int i = sd1.Length;
                        if (i == 1)
                        {
                            return Sourcepath + "/" + Relativepath;
                        }
                        else
                        {
                            string sf = "http://";
                            for (int j = 0; j < i - 1; j++)
                            {
                                sf = sf + sd1[j] + "/";
                            }
                            return sf + Relativepath;
                        }
                    }
                }
                else
                {
                    string[] sd1 = Sourcepath.Replace("http://", "").Split('/');
                    int i = sd1.Length;
                    int n = 0;
                    string[] sd2 = Relativepath.Split('/');
                    int k = sd2.Length;
                    string kd = "";
                    for (int j = 0; j < k; j++)
                    {
                        if (sd2[j] == "..")
                        {
                            n = n + 1;
                        }
                        else
                        {
                            kd = kd + "/" + sd2[j];
                        }
                    }
                    //kd = kd.Substring(0, kd.Length - 1);


                    string sf = "http://";
                    for (int j = 0; j < i - n - 1; j++)
                    {
                        sf = sf + sd1[j] + "/";
                    }
                    return sf.Substring(0, sf.Length - 1) + kd;
                }
            }
        }
        #region 采集
        /// <summary>
        /// 获取指定远程网页内容
        /// </summary>
        /// <param name="strUrl">所要查找的远程网页地址</param>
        /// <param name="timeout">超时时长设置，一般设置为8000</param>
        /// <param name="enterType">是否输出换行符，0不输出，1输出文本框换行</param>
        /// <param name="EnCodeType">编码方式</param>
        public static string GetRequestString(string strUrl, int timeout, int enterType, Encoding EnCodeType, params string[] Parms)
        {
            string strResult;
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                //System.Net.Cache.HttpRequestCachePolicy noCachePolicy = new System.Net.Cache.HttpRequestCachePolicy(System.Net.Cache.HttpRequestCacheLevel.NoCacheNoStore);
                //myReq.CachePolicy = noCachePolicy;
                myReq.Method = "GET";
                myReq.KeepAlive = true;
                Uri baseUri = new Uri(strUrl);
                myReq.Timeout = timeout;
                myReq.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
                myReq.Headers["Accept-Language"] = "zh-cn,zh;q=0.5";
                myReq.Headers["Accept-Charset"] = "GB2312,utf-8;q=0.7,*;q=0.7";
                if (Parms != null)
                {
                    if (Parms[0] != "null")
                    {
                        if (!string.IsNullOrEmpty(Parms[0]))
                            myReq.Headers["Cookie"] = Parms[0];
                        if (Parms.Length > 1 && !string.IsNullOrEmpty(Parms[1]))
                        {
                            myReq.Referer = Utils.UrlEncode(Parms[1]);
                        }
                    }

                }
                else
                {
                    if (string.IsNullOrEmpty(myReq.Referer))
                    {
                        myReq.Referer = baseUri.DnsSafeHost;
                    }
                }
                myReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
              
               myReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
                myReq.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;//自动解压缩

                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();

                StringBuilder sb = new StringBuilder(40960);
                try
                {

                    Stream myStream = HttpWResp.GetResponseStream();
                    StreamReader sr = new StreamReader(myStream, EnCodeType);
                    while (!sr.EndOfStream)
                    {
                        sb.Append(sr.ReadLine());
                        if (enterType != 1)
                        {
                            sb.Replace("\r\n", "");
                            sb.Replace("\r", "");
                            sb.Replace("\n", "");
                        }
                    }

                    sr.Close();
                    sr.Dispose();
                    myStream.Close();
                    myStream.Dispose();
                }
                catch (Exception ex)
                {
                    strResult = strUrl + "请求错误：" + ex.Message;
                    throw new Exception(strUrl + "请求错误：" + ex.Message);
                }
                finally
                {
                    HttpWResp.Close();
                }

                strResult = sb.ToString();
            }
            catch (Exception err)
            {
                strResult = strUrl + "请求错误：" + err.Message;
                throw new Exception(strUrl + "请求错误：" + err.Message);

            }
            return strResult;
        }
        #endregion
        #endregion

       
        #region 返回指定IP是否在指定的IP数组所限定的范围内
        /// <summary>
        /// 返回指定IP是否在指定的IP数组所限定的范围内, IP数组内的IP地址可以使用*表示该IP段任意, 例如192.168.1.*
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="iparray"></param>
        /// <returns></returns>
        public static bool IsIPInArray(string ip, string[] iparray)
        {
            bool rbool = false;
            string[] userip = Utils.SplitString(ip, @".");
            string[] tmpip=null;
            for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++)
            {
                tmpip = Utils.SplitString(iparray[ipIndex], @".");
                int r = 0;
                for (int i = 0; i < tmpip.Length; i++)
                {
                    if (tmpip[i] == "*")
                    {
                        rbool= true;
                    }

                    if (userip.Length > i)
                    {
                        if (tmpip[i] == userip[i])
                        {
                            r++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }

                }
                if (r == 4)
                {
                    rbool= true;
                }


            }
            userip = null;
            tmpip = null;
            return rbool;

        }
        #endregion

        #region 是否web
        /// <summary>
        /// 是否web
        /// </summary>
        /// <returns></returns>
        public static bool IsWeb()
        {
            if (System.Web.HttpContext.Current != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 获取ip
        /// <summary>
        /// 获取ip
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            string ip = DNTRequest.GetIP();

            return ip;
        }
        #endregion

        #region Sql操作
        /// <summary>
        /// 检测是否有Sql危险字符
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(string str)
        {

            return !Regex.IsMatch(str, @"[\']");
        }

        /// <summary>
        /// 格式化字符串,符合SQL语句
        /// </summary>
        /// <param name="formatStr">需要格式化的字符串</param>
        /// <returns>字符串</returns>
        public static string inSQL(string formatStr)
        {
            string rStr = formatStr;
            if (formatStr != null && formatStr != string.Empty)
            {
                rStr = rStr.Replace("'", "''");
                //rStr = rStr.Replace("\"", "\"\"");
            }
            return rStr;
        }
        /// <summary>
        /// 格式化字符串,是inSQL的反向
        /// </summary>
        /// <param name="formatStr"></param>
        /// <returns></returns>
        public static string outSQL(string formatStr)
        {
            string rStr = formatStr;
            if (rStr != null)
            {
                rStr = rStr.Replace("''", "'");
                rStr = rStr.Replace("\"\"", "\"");
            }
            return rStr;
        }
        #endregion

        #region cookie操作
        #region "获取当前Cookies名称"
        /// <summary>
        /// "获取当前Cookies名称
        /// </summary>
        public static string GetCookiesName
        {
            get
            {
                return "CMN_cookies";
            }
        }
        #endregion

        #region "获取登陆用户UserID"
        /// <summary>
        /// 获取登陆用户UserID,如果未登陆为0
        /// </summary>
        public static int GetUserID
        {
            get
            {
                return HttpContext.Current.User.Identity.IsAuthenticated ? Convert.ToInt32(HttpContext.Current.User.Identity.Name) : 0;
            }

        }
        #endregion

        /// <summary>
        /// md5前缀
        /// </summary>
        public static string GetMD5Prefix = "CMNCMSMD5";

        #region "获得sessionid"
        /// <summary>
        /// 获得sessionid
        /// </summary>
        public static string GetSessionID
        {
            get
            {
                return HttpContext.Current.Session.SessionID;
            }
        }
        #endregion

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        public static void WriteCookie(string strName, string strValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            HttpContext.Current.Response.AppendCookie(cookie);

        }
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="strValue">过期时间(分钟)</param>
        public static void WriteCookie(string strName, string strValue, int expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            cookie.Expires = DateTime.Now.AddMinutes(expires);
            HttpContext.Current.Response.AppendCookie(cookie);

        }

        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(string strName)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
            {
                return HttpContext.Current.Request.Cookies[strName].Value.ToString();
            }

            return "";
        }
        #endregion 

        #region js操作

        #region "替换JS中特殊字符"
        /// <summary>
        /// 将JS中的特殊字符替换
        /// </summary>
        /// <param name="str">要替换字符</param>
        /// <returns></returns>
        public static string ReplaceJs(string str)
        {

            if (str != null)
            {
                str = str.Replace("\"", "&quot;");
                str = str.Replace("(", "&#40;");
                str = str.Replace(")", "&#41;");
                str = str.Replace("%", "&#37;");
            }

            return str;

        }
        #endregion

        #region "js信息提示框"
        /// <summary>
        /// js信息提示框
        /// </summary>
        /// <param name="Message">提示信息文字</param>
        /// <param name="ReturnUrl">返回地址</param>
        /// <param name="rq"></param>
        public static void JsMessBox(string Message, string ReturnUrl, HttpContext rq)
        {
            System.Text.StringBuilder msgScript = new System.Text.StringBuilder();
            msgScript.Append("<script language=JavaScript>\n");
            msgScript.Append("alert(\"" + Message + "\");\n");
            msgScript.Append("parent.location.href='" + ReturnUrl + "';\n");
            msgScript.Append("</script>\n");
            rq.Response.Write(msgScript.ToString());
            rq.Response.End();
        }

        /// <summary>
        /// 弹出Alert信息窗
        /// </summary>
        /// <param name="Message">信息内容</param>
        public static void JsMessBox(string Message)
        {
            System.Text.StringBuilder msgScript = new System.Text.StringBuilder();
            msgScript.Append("<script language=JavaScript>\n");
            msgScript.Append("alert(\"" + Message + "\");\n");
            msgScript.Append("</script>\n");
            HttpContext.Current.Response.Write(msgScript.ToString());
        }

        #endregion

        #endregion 

        #region "获取用户Form,Post提交字段值"
        /// <summary>
        /// 获取mvc form 提交值
        /// </summary>
        /// <param name="InputName">字段名</param>
        /// <param name="controller">mvc Controller 实例</param>
        /// <param name="MaxLen">最大允许字符长度 0为不限制</param>
        /// <param name="MinLen">最小字符长度 0为不限制</param>
        /// <param name="DataType">字段数值类型 int 和str和dat不限为为空</param>
        /// <returns></returns>
        public static object GetQueryAndFormString(string InputName, System.Web.Mvc.Controller controller, int MaxLen, int MinLen, DataType DataType)
        {
          
            string TempValue = "";

            #region "获取提交字段数据TempValue"
                if (controller.Request.Form[InputName] != null)
                {
                    TempValue = controller.Request.Form[InputName];//.ToString();
                }
               
           
            #endregion




            return GetQueryAndFormString(TempValue, MaxLen, MinLen, DataType);


        }
        /// <summary>
        /// 获取mvc form 提交值
        /// </summary>
        /// <param name="InputName">字段名</param>
        /// <param name="controller">mvc Controller 实例</param>
        /// <param name="Method">获取方法</param>
        /// <param name="MaxLen">最大允许字符长度 0为不限制</param>
        /// <param name="MinLen">最小字符长度 0为不限制</param>
        /// <param name="DataType">字段数值类型 int 和str和dat不限为为空</param>
        /// <returns></returns>
        public static object GetQueryAndFormString(string InputName, System.Web.Mvc.Controller controller, MethodType Method, int MaxLen, int MinLen, DataType DataType)
        {
            string TempValue = "";
            if (Method == MethodType.Post)
            {
                if (controller.Request.Form[InputName] != null)
                {
                    TempValue = controller.Request.Form[InputName];//.ToString();
                }
            }
            else if (Method == MethodType.Get)
            {
                if (controller.Request.QueryString[InputName] != null)
                {
                    TempValue = controller.Request.QueryString[InputName];//.ToString();
                }
            }

            return GetQueryAndFormString(TempValue, MaxLen, MinLen, DataType);
        }

        /// <summary>
        /// 获取post和get提交值
        /// </summary>
        /// <param name="InputName">字段名</param>
        /// <param name="Method">post和get</param>
        /// <param name="MaxLen">最大允许字符长度 0为不限制</param>
        /// <param name="MinLen">最小字符长度 0为不限制</param>
        /// <param name="DataType">字段数值类型 int 和str和dat不限为为空</param>
        /// <returns></returns>
        public static object GetQueryAndFormString(string InputName, MethodType Method, int MaxLen, int MinLen, DataType DataType)
        {
            HttpContext rq = HttpContext.Current;
            string TempValue = "";
            
            #region "获取提交字段数据TempValue"
            if (Method == MethodType.Post)
            {
                if (rq.Request.Form[InputName] != null)
                {
                    TempValue = rq.Request.Form[InputName].ToString();
                }
            }
            else if (Method == MethodType.Get)
            {
                if (rq.Request.QueryString[InputName] != null)
                {
                    TempValue = rq.Request.QueryString[InputName].ToString();
                }
            }
           
            else
            {
                throw new Exception(string.Format("获取数据失败,{0}字段提交数据方式不是post或get或form!", InputName));
                // EventMessage.MessageBox(2, "获取数据失败", string.Format("{0}字段提交数据方式不是post和get!", InputName), Icon_Type.Error, "history.back();", UrlType.JavaScript);
            }
            #endregion
            return GetQueryAndFormString(TempValue, MaxLen, MinLen, DataType);


        }
        /// <summary>
        /// 获取post提交值
        /// </summary>
        /// <param name="TempValue"></param>
        /// <param name="Method">post和get</param>
        /// <param name="MaxLen">最大允许字符长度 0为不限制</param>
        /// <param name="MinLen">最小字符长度 0为不限制</param>
        /// <param name="DataType">字段数值类型 int 和str和dat不限为为空</param>
        /// <returns></returns>
        public static object GetQueryAndFormString(string iValue, int MaxLen, int MinLen, DataType DataType)
        {


            #region "检测最大允许长度"
            if (MaxLen != 0)
            {
                if (iValue.Length > MaxLen)
                {
                    throw new Exception(string.Format("输入数据格式验证失败,字段值：{0}超过系统允许长度{1}!", iValue, MaxLen));
                    //EventMessage.MessageBox(2, "输入数据格式验证失败", string.Format("字段值：{0}超过系统允许长度{1}!", iValue, MaxLen), Icon_Type.Error, "history.back();", UrlType.JavaScript);
                }
            }
            #endregion

            #region "检测最小允许长度"
            if (MinLen != 0)
            {
                if (iValue.Length < MinLen)
                {
                    throw new Exception(string.Format("输入数据格式验证失败,字段值：{0}低于系统允许长度{1}!", iValue,MinLen));
                    //EventMessage.MessageBox(2, "输入数据格式验证失败", string.Format("字段值：{0}低于系统允许长度{1}!", iValue, MinLen), Icon_Type.Error, "history.back();", UrlType.JavaScript);
                }
            }
            #endregion

            #region "检测数据类型"
            if (iValue != "")
            {
                RegExpression.RegExpressionBase reg;
                switch (DataType)
                {
                    case DataType.Int:
                        int IntTempValue = 0;
                        if (!int.TryParse(iValue, out IntTempValue))
                            throw new Exception(string.Format("输入数据格式验证失败,字段值：{0}数据类型必需为Int型!", iValue, MaxLen));
                            //EventMessage.MessageBox(2, "输入数据格式验证失败", string.Format("字段值：{0}数据类型必需为Int型!", iValue), Icon_Type.Error, "history.back();", UrlType.JavaScript);
                        return IntTempValue;
                    case DataType.Dat:
                        DateTime DateTempValue = DateTime.MinValue;
                        if (!DateTime.TryParse(iValue, out DateTempValue))
                            throw new Exception(string.Format("输入数据格式验证失败,字段值：{0}数据类型必需为日期型!", iValue, MaxLen));
                            //EventMessage.MessageBox(2, "输入数据格式验证失败", string.Format("字段值：{0}数据类型必需为日期型!", iValue), Icon_Type.Error, "history.back();", UrlType.JavaScript);
                        return DateTempValue;
                    case DataType.Long:
                        long LongTempValue = long.MinValue;
                        if (!long.TryParse(iValue, out LongTempValue))
                            throw new Exception(string.Format("输入数据格式验证失败,字段值：{0}数据类型必需为Log型!", iValue, MaxLen));
                            //EventMessage.MessageBox(2, "输入数据格式验证失败", string.Format("字段值：{0}数据类型必需为Log型!", iValue), Icon_Type.Error, "history.back();", UrlType.JavaScript);
                        return LongTempValue;
                    case DataType.Double:
                        double DoubleTempValue = double.MinValue;
                        if (!double.TryParse(iValue, out DoubleTempValue))
                            throw new Exception(string.Format("输入数据格式验证失败,字段值：{0}数据类型必需为Double型!", iValue, MaxLen));
                            //EventMessage.MessageBox(2, "输入数据格式验证失败", string.Format("字段值：{0}数据类型必需为Double型!", iValue), Icon_Type.Error, "history.back();", UrlType.JavaScript);
                        return DoubleTempValue;
                    case DataType.CharAndNum:
                        reg = new CMN.Common.RegExpression.NumAndStringRegExpression();
                        if (!reg.IsMatch(iValue))
                            throw new Exception(string.Format("输入数据格式验证失败,字段值：{0}数据类型必需为英文或数字!", iValue, MaxLen));
                            //EventMessage.MessageBox(2, "输入数据格式验证失败", string.Format("字段值：{0}数据类型必需为英文或数字!", iValue), Icon_Type.Error, "history.back();", UrlType.JavaScript);
                        return iValue;
                    case DataType.CharAndNumAndChinese:
                        reg = new CMN.Common.RegExpression.NumAndStringAndChineseRegExpression();
                        if (!reg.IsMatch(iValue))
                            throw new Exception(string.Format("输入数据格式验证失败,字段值：{0}数据类型必需为英文或数字或中文!", iValue, MaxLen));
                            //EventMessage.MessageBox(2, "输入数据格式验证失败", string.Format("字段值：{0}数据类型必需为英文或数字或中文!", iValue), Icon_Type.Error, "history.back();", UrlType.JavaScript);
                        return iValue;
                    case DataType.Email:
                        reg = new CMN.Common.RegExpression.EmailRegExpression();
                        if (!reg.IsMatch(iValue))
                            throw new Exception(string.Format("输入数据格式验证失败,字段值：{0}数据类型必需为邮件地址!", iValue, MaxLen));
                            //EventMessage.MessageBox(2, "输入数据格式验证失败", string.Format("字段值：{0}数据类型必需为邮件地址!", iValue), Icon_Type.Error, "history.back();", UrlType.JavaScript);
                        return iValue;
                    case DataType.Byte:
                        byte bt = new byte();
                        if (!byte.TryParse(iValue, out bt))
                        {
                            throw new Exception(string.Format("输入数据格式验证失败,{0}字段值：数据类型必需为Byte型!", iValue, MaxLen));
                            //EventMessage.MessageBox(2, "输入数据格式验证失败", string.Format("{0}字段值：数据类型必需为Byte型!", iValue), Icon_Type.Error, "history.back();", UrlType.JavaScript);
                        }
                        return bt;
                    case DataType.Bool:
                        switch (iValue)
                        {
                            case "0":
                                {
                                     return false;
                                    
                                }
                            case "1":
                                { return true;
                                    
                                }
                            case "false":
                                {
                                     return false;
                                    
                                }
                            case "true":
                                { return true;
                                    
                                }
                            default :{
                                    throw new Exception(string.Format("输入数据格式验证失败,{0}字段值：数据类型必需为Bool型!", iValue, MaxLen));
                                    
                                }
                        }
                        break;
                    case DataType.Decimal:
                       decimal dec =new decimal();
                       dec = 0;
                       if (!decimal.TryParse(iValue, out dec))
                       {
                           throw new Exception(string.Format("输入数据格式验证失败,{0}字段值：数据类型必需为decimal型!", iValue, MaxLen));
                       }
                       return dec; break;
                    default:
                        return iValue;
                }

            }
            else
            {
                switch (DataType)
                {
                    case DataType.Int:
                        return 0;
                    case DataType.Dat:
                        return null;
                    case DataType.Long:
                        return long.MinValue;
                    case DataType.Double:
                        return 0.0f;
                    case DataType.Byte:
                        byte myByte = 0;
                        return myByte;
                    case DataType.Bool:
                        return false;
                    default:
                        return iValue;
                }
            }

            #endregion
        }

        #endregion

        #region "获取WEBCache名称前辍"
        /// <summary>
        /// 获取WEBCache名称前辍
        /// </summary>
        public static string GetWebCacheName
        {
            get
            {
                return "CMN_WebCache";
            }
        }
        #endregion

        #region 合并数组List
        /// <summary>
        /// 合并list
        /// </summary>
        /// <param name="lst">合并list1</param>
        /// <param name="lst2">合并list2</param>
        /// <returns>list</returns>
        public static List<string> CombineList(List<string> lst, List<string> lst2)
        {
            List<string> lstTemp = new List<string>();
            for (int i = 0; i < lst.Count; i++)
            {
                if (!lstTemp.Contains(lst[i]))
                {
                    lstTemp.Add(lst[i]);
                }

            }
            for (int i = 0; i < lst2.Count; i++)
            {
                if (!lstTemp.Contains(lst2[i]))
                {
                    lstTemp.Add(lst2[i]);
                }

            }
            return lstTemp;
        }

        #endregion 
        #region datatable to json  数组
        /// <summary>
        /// 将dt转化成Json数据 格式如 table[{id:1,title:'体育'},id:2,title:'娱乐'}]
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTableToJSON(DataTable dt, int totalPorperty)
        {
            return DataTableToJSON(dt, 0, "totalPorperty", "root", totalPorperty);
        }
        public static string DataTableToJSON(DataTable dt, int fromCount, int totalPorperty)
        {
            return DataTableToJSON(dt, fromCount, "totalPorperty", "root", totalPorperty);
        }
        /// <summary>
        /// 将dt转化成Json数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="fromCount"></param>
        /// <param name="totalCountStr"></param>
        /// <param name="tbname"></param>
        /// <returns></returns>
        public static string DataTableToJSON(DataTable dt, int fromCount, string totalCountStr, string tbname, int totalPorperty)
        {
            return DataTableToJSON(dt, fromCount, "totalPorperty", "root", true, totalPorperty);
        }
        /// <summary>
        /// 将dt转化成Json数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="fromCount"></param>
        /// <param name="totalCountStr"></param>
        /// <param name="tbname"></param>
        /// <returns></returns>
        public static string DataTableToJSON(DataTable dt, int fromCount, string totalCountStr, string tbname, bool formatData, int totalPorperty)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{" + totalCountStr + ":" + totalPorperty + "," + tbname + ": [");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i > 0)
                    jsonBuilder.Append(",");
                jsonBuilder.Append("{");
                jsonBuilder.Append("no:" + (fromCount + i + 1) + ",");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (j > 0)
                        jsonBuilder.Append(",");
                    if (dt.Columns[j].DataType.Equals(typeof(DateTime)) && dt.Rows[i][j].ToString() != "")
                        jsonBuilder.Append(dt.Columns[j].ColumnName + ": '" + Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy-MM-dd hh:mm:ss") + "'");
                    else if (dt.Columns[j].DataType.Equals(typeof(String)))
                        jsonBuilder.Append(dt.Columns[j].ColumnName + ": '" + dt.Rows[i][j].ToString().Replace("\\", "\\\\").Replace("\'", "\\\'").Replace("\t", " ").Replace("\r", " ").Replace("\n", "<br/>") + "'");
                    else
                        jsonBuilder.Append(dt.Columns[j].ColumnName + ": '" + dt.Rows[i][j].ToString() + "'");
                }
                jsonBuilder.Append("}");
            }
            jsonBuilder.Append("]}");
            return jsonBuilder.ToString();

        }
        /// <summary>
        /// 将DataTable转换为list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt)
        {
            if (dt == null)
                return null;
            List<T> result = new List<T>();
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                T _t = (T)Activator.CreateInstance(typeof(T));
                System.Reflection.PropertyInfo[] propertys = _t.GetType().GetProperties();
                foreach (System.Reflection.PropertyInfo pi in propertys)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        // 属性与字段名称一致的进行赋值 
                        if (pi.Name.ToLower().Equals(dt.Columns[i].ColumnName.ToLower()))
                        {
                            if (dt.Rows[j][i] != DBNull.Value)
                            {
                                if (pi.PropertyType.ToString() == "System.Int32")
                                {
                                    pi.SetValue(_t, Int32.Parse(dt.Rows[j][i].ToString()), null);
                                }
                                else if (pi.PropertyType.ToString() == "System.DateTime")
                                {
                                    pi.SetValue(_t, Convert.ToDateTime(dt.Rows[j][i].ToString()), null);
                                }
                                else if (pi.PropertyType.ToString() == "System.Boolean")
                                {
                                    pi.SetValue(_t, Convert.ToBoolean(dt.Rows[j][i].ToString()), null);
                                }
                                else if (pi.PropertyType.ToString() == "System.Single")
                                {
                                    pi.SetValue(_t, Convert.ToSingle(dt.Rows[j][i].ToString()), null);
                                }
                                else if (pi.PropertyType.ToString() == "System.Double")
                                {
                                    pi.SetValue(_t, Convert.ToDouble(dt.Rows[j][i].ToString()), null);
                                }
                                else
                                {
                                    pi.SetValue(_t, dt.Rows[j][i].ToString(), null);
                                }
                            }
                            else
                                pi.SetValue(_t, "", null);//为空，但不为Null
                            break;
                        }
                    }
                }
                result.Add(_t);
            }
            return result;
        }
        #endregion 

        #region "设置页面不被缓存"
        /// <summary>
        /// 设置页面不被缓存
        /// </summary>
        public static void SetPageNoCache()
        {

            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.CacheControl = "no-cache";
            HttpContext.Current.Response.AddHeader("Pragma", "No-Cache");
        }
        #endregion

        #region 生成0-9随机数
        /// <summary>
        /// 生成0-9随机数
        /// </summary>
        /// <param name="VcodeNum">生成长度</param>
        /// <returns></returns>
        public static string RndNum(int VcodeNum)
        {
            StringBuilder sb = new StringBuilder(VcodeNum);
            Random rand = new Random();
            for (int i = 1; i < VcodeNum + 1; i++)
            {
                int t = rand.Next(9);
                sb.AppendFormat("{0}", t);
            }
            return sb.ToString();

        }
        
        /// <summary>
        /// 生成随机26个字符窜
        /// </summary>
        /// <param name="VcodeNum"></param>
        /// <returns></returns>
        public static string RndChar(int VcodeNum)
        {
            string codestr = "abcdefghijklimnopqrstuvwxyz";
            int number;
            string checkCode = String.Empty;
            Random rnd = new Random();

            for (int i = 0; i <  VcodeNum; i++)
            {
                number = rnd.Next(0, 26);
                checkCode = string.Concat(checkCode, codestr.Substring(number, 1));
            }
            return checkCode;

        }
        #endregion

        #region +++页面url

        #region 返回URL中结尾的文件名

        /// <summary>
        /// 返回URL来路
        /// </summary>		
        public static string GetUrlReferrer()
        {
            return HttpContext.Current.Request.UrlReferrer != null ? HttpContext.Current.Request.UrlReferrer.ToString() : string.Empty;
        }

        ///// <summary>
        ///// 获取url参数值
        ///// </summary>
        ///// <param name="strUrl"></param>
        ///// <param name="strQuery"></param>
        ///// <returns></returns>
        //public static string GetUrlRequestQuery(string strUrl, string strQueryName)
        //{
        //    string strQuery = GetURLFilename(strUrl);

        //}

        /// <summary>
        /// 返回URL中结尾的文件名
        /// </summary>		
        public static string GetURLFilename(string url)
        {
            if (url == null)
            {
                return "";
            }
            string[] strs1 = url.Split(new char[] { '/' });
            return strs1[strs1.Length - 1].Split(new char[] { '?' })[0];
        }
        #endregion 
        /// <summary>
        /// 获取当前访问页面地址
        /// </summary>
        public static string GetScriptName
        {
            get
            {
                return HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"].ToString();
            }
        }

        /// <summary>
        /// 检测当前url是否包含指定的字符
        /// </summary>
        /// <param name="sChar">要检测的字符</param>
        /// <returns></returns>
        public static bool CheckScriptNameChar(string sChar)
        {
            bool rBool = false;
            if (GetScriptName.ToLower().LastIndexOf(sChar) >= 0)
                rBool = true;
            return rBool;
        }

        /// <summary>
        /// 获取当前页面的扩展名
        /// </summary>
        public static string GetScriptNameExt
        {
            get
            {
                return GetScriptName.Substring(GetScriptName.LastIndexOf(".") + 1);
            }
        }

        /// <summary>
        /// 获取当前访问页面地址参数
        /// </summary>
        public static string GetScriptNameQueryString
        {
            get
            {
                return HttpContext.Current.Request.ServerVariables["QUERY_STRING"].ToString();
            }
        }

        /// <summary>
        /// 获得页面文件名和参数名
        /// </summary>
        public static string GetScriptNameUrl
        {
            get
            {
                string Script_Name = GetScriptName;
                Script_Name = Script_Name.Substring(Script_Name.LastIndexOf("/") + 1);
                Script_Name += "?" + GetScriptNameQueryString;
                return Script_Name;
            }
        }

        /// <summary>
        /// 获取当前访问页面Url
        /// </summary>
        public static string GetScriptUrl
        {
            get
            {
                return GetScriptNameQueryString == "" ? GetScriptName : string.Format("{0}?{1}",GetScriptName, GetScriptNameQueryString);
            }
        }

        /// <summary>
        /// 返回当前页面目录的url
        /// </summary>
        /// <param name="FileName">文件名</param>
        /// <returns></returns>
        public static string GetHomeBaseUrl(string FileName)
        {
            string Script_Name = GetScriptName;
            return string.Format("{0}/{1}", Script_Name.Remove(Script_Name.LastIndexOf("/")), FileName);
        }

        /// <summary>
        /// 返回当前网站网址
        /// </summary>
        /// <returns></returns>
        public static string GetHomeUrl()
        {
            return HttpContext.Current.Request.Url.Authority;
        }

        /// <summary>
        /// 获取当前访问文件物理目录
        /// </summary>
        /// <returns>路径</returns>
        public static string GetScriptPath
        {
            get
            {
                string Paths = HttpContext.Current.Request.ServerVariables["PATH_TRANSLATED"].ToString();
                return Paths.Remove(Paths.LastIndexOf("\\"));
            }
        }
        #endregion

        #region "+++加密"

        #region "3des加密字符串"
        /// <summary>
        /// 3des加密函数(ECB加密模式,PaddingMode.PKCS7,无IV)
        /// </summary>
        /// <param name="encryptValue">加密字符</param>
        /// <param name="key">加密key(24字符)</param>
        /// <returns>加密后Base64字符</returns>
        public static string EncryptString(string encryptValue, string key)
        {
            string enstring = "加密出错!";
            ICryptoTransform ct; //需要此接口才能在任何服务提供程序上调用 CreateEncryptor 方法，服务提供程序将返回定义该接口的实际 encryptor 对象。
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            SymmetricAlgorithm des3 = SymmetricAlgorithm.Create("TripleDES");
            des3.Mode = CipherMode.ECB;
            des3.Key = Encoding.UTF8.GetBytes(GetSubStringLen(key, 24, '0'));
            //des3.KeySize = 192;
            des3.Padding = PaddingMode.PKCS7;

            ct = des3.CreateEncryptor();

            byt = Encoding.UTF8.GetBytes(encryptValue);//将原始字符串转换成字节数组。大多数 .NET 加密算法处理的是字节数组而不是字符串。

            //创建 CryptoStream 对象 cs 后，现在使用 CryptoStream 对象的 Write 方法将数据写入到内存数据流。这就是进行实际加密的方法，加密每个数据块时，数据将被写入 MemoryStream 对象。

            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            try
            {
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();
                enstring = Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                enstring = ex.ToString();
            }
            finally
            {
                cs.Close();
                cs.Dispose();
                ms.Close();
                ms.Dispose();
                des3.Clear();
                ct.Dispose();
            }
            return enstring;
        }
        #endregion

        #region "3des解密字符串"
        /// <summary>
        /// 3des解密函数(ECB加密模式,PaddingMode.PKCS7,无IV)
        /// </summary>
        /// <param name="decryptString">解密字符</param>
        /// <param name="key">解密key(24字符)</param>
        /// <returns>解密后字符</returns>
        public static string DecryptString(string decryptString, string key)
        {
            string destring = "解密字符失败!";
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;

            SymmetricAlgorithm des3 = SymmetricAlgorithm.Create("TripleDES");
            des3.Mode = CipherMode.ECB;
            des3.Key = Encoding.UTF8.GetBytes(GetSubStringLen(key, 24, '0'));
            //des3.KeySize = 192;
            des3.Padding = PaddingMode.PKCS7;

            ct = des3.CreateDecryptor();

            byt = Convert.FromBase64String(decryptString);

            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            try
            {
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();
                destring = Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                destring = ex.ToString();
            }
            finally
            {
                ms.Close();
                cs.Close();
                ms.Dispose();
                cs.Dispose();
                ct.Dispose();
                des3.Clear();
            }
            return destring;
        }
        #endregion
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">加密字符</param>
        /// <param name="code">加密位数16/32</param>
        /// <returns></returns>
        public static string Md5(string str, int code)
        {
            string strEncrypt = string.Empty;
            if (code == 16)
            {
                strEncrypt = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").Substring(8, 16);
            }
            else if (code == 32)
            {
                strEncrypt = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
            }

            return strEncrypt;
        }
        #endregion


        #region +++类型转换

        #region  根据阿拉伯数字返回月份的名称(可更改为某种语言)
        /// <summary>
        /// 根据阿拉伯数字返回月份的名称(可更改为某种语言)
        /// </summary>	
        public static string[] GetEnMonthes
        {
            get
            {
                return new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
            }
        }
        #endregion 


        #region 是否是Double
        public static bool IsDouble(object Expression)
        {
            return TypeParse.IsDouble(Expression);
        }
        #endregion


        #region 判断对象是否为Int32类型的数字
        /// <summary>
        /// 判断对象是否为Int32类型的数字
        /// </summary>
        /// <param name="Expression"></param>
        /// <returns></returns>
        public static bool IsNumeric(object Expression)
        {
            return TypeParse.IsNumeric(Expression);
        }
        #endregion

        #region  去掉byte[] 中特定的byte
        /// <summary> 
        /// 去掉byte[] 中特定的byte 
        /// </summary> 
        /// <param name="b"> 需要处理的byte[] </param> 
        /// <param name="cut">byte[] 中需要除去的特定 byte (此处: byte cut = 0x00 ;) </param> 
        /// <returns> 返回处理完毕的byte[] </returns> 
        public static byte[] ByteCut(byte[] b, byte cut)
        {
            List<byte> list = new List<byte>();
            list.AddRange(b);
            for (int i = list.Count - 1; i >= 0; i--)
            {
                if (list[i] == cut)
                    list.RemoveAt(i);
            }
            byte[] lastbyte = new byte[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                lastbyte[i] = list[i];
            }
            list = null;
            return lastbyte;
        }
        #endregion  

        #region  字节数组转16进制字符串
        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ByteToHexStr(byte[] bytes)
        {
            StringBuilder sb = new StringBuilder();
            string strReturn;
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.Append(bytes[i].ToString("X2"));
                }
            }
            strReturn = sb.ToString();
            sb.Remove(0, sb.Length);
            return strReturn;
        }
        #endregion   

        #region 字符串转16进制字节数组
        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        private static byte[] StringToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
        #endregion 

        #region  字符串转换成16进制
        /// <summary>
        /// 将字符串转换成16进制
        /// </summary>
        /// <param name="strHex"></param>
        /// <returns></returns>
        public static string StringToHex(string strHex)
        {

            char[] values = strHex.ToCharArray();
            string hexOutput = string.Empty;
            StringBuilder sb = new StringBuilder();
            foreach (char letter in values)
            {
                // Get the integral value of the character.
                int value = Convert.ToInt32(letter);
                // Convert the decimal value to a hexadecimal value in string form.
                sb.Append(String.Format("{0:X}", value));

            }
            values = null;
            hexOutput = sb.ToString();
            sb.Remove(0, sb.Length);
            return hexOutput;
        }
        #endregion

        #region 16进制和汉字转换
        /// <summary>
        /// 从汉字转换到16进制
        /// </summary>
        /// <param name="s"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符用逗号分隔</param>
        /// <returns></returns>
        public static string ChineseToHex(string s, string charset, bool fenge)
        {
            if ((s.Length % 2) != 0)
            {
                s += " ";//空格
                //throw new ArgumentException("s is not valid chinese string!");
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            byte[] bytes = chs.GetBytes(s);
            string str = string.Empty;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.Append(string.Format("{0:X}", bytes[i]));
                if (fenge && (i != bytes.Length - 1))
                {
                    sb.Append(string.Format("{0}", ","));
                }
            }
            bytes = null;
            str = sb.ToString();
            sb.Remove(0, sb.Length);
            return str.ToLower();
        }
       
        ///<summary>
        /// 从16进制转换成汉字
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string ChineseUnHex(string hex, string charset)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\\", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
            }
            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hex.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message. 
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            string strRetun=chs.GetString(bytes);
            bytes=null;
            return strRetun;
        }
        #endregion 

        #region  转换人民币大小金额
        /// <summary> 
        /// 转换人民币大小金额 
        /// </summary> 
        /// <param name="num">金额</param> 
        /// <returns>返回大写形式</returns> 
        public static string NumToRMB(decimal num)
        {
            string str1 = "零壹贰叁肆伍陆柒捌玖";            //0-9所对应的汉字 
            string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字 
            string str3 = "";    //从原num值中取出的值 
            string str4 = "";    //数字的字符串形式 
            string str5 = "";  //人民币大写金额形式 
            int i;    //循环变量 
            int j;    //num的值乘以100的字符串长度 
            string ch1 = "";    //数字的汉语读法 
            string ch2 = "";    //数字位的汉字读法 
            int nzero = 0;  //用来计算连续的零值是几个 
            int temp;            //从原num值中取出的值 

            num = Math.Round(Math.Abs(num), 2);    //将num取绝对值并四舍五入取2位小数 
            str4 = ((long)(num * 100)).ToString();        //将num乘100并转换成字符串形式 
            j = str4.Length;      //找出最高位 
            if (j > 15) { return "溢出"; }
            str2 = str2.Substring(15 - j);   //取出对应位数的str2的值。如：200.55,j为5所以str2=佰拾元角分 

            //循环取出每一位需要转换的值 
            for (i = 0; i < j; i++)
            {
                str3 = str4.Substring(i, 1);          //取出需转换的某一位的值 
                temp = Convert.ToInt32(str3);      //转换为数字 
                if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                {
                    //当所取位数不为元、万、亿、万亿上的数字时 
                    if (str3 == "0")
                    {
                        ch1 = "";
                        ch2 = "";
                        nzero = nzero + 1;
                    }
                    else
                    {
                        if (str3 != "0" && nzero != 0)
                        {
                            ch1 = "零" + str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                    }
                }
                else
                {
                    //该位是万亿，亿，万，元位等关键位 
                    if (str3 != "0" && nzero != 0)
                    {
                        ch1 = "零" + str1.Substring(temp * 1, 1);
                        ch2 = str2.Substring(i, 1);
                        nzero = 0;
                    }
                    else
                    {
                        if (str3 != "0" && nzero == 0)
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            if (str3 == "0" && nzero >= 3)
                            {
                                ch1 = "";
                                ch2 = "";
                                nzero = nzero + 1;
                            }
                            else
                            {
                                if (j >= 11)
                                {
                                    ch1 = "";
                                    nzero = nzero + 1;
                                }
                                else
                                {
                                    ch1 = "";
                                    ch2 = str2.Substring(i, 1);
                                    nzero = nzero + 1;
                                }
                            }
                        }
                    }
                }
                if (i == (j - 11) || i == (j - 3))
                {
                    //如果该位是亿位或元位，则必须写上 
                    ch2 = str2.Substring(i, 1);
                }
                str5 = str5 + ch1 + ch2;

                if (i == j - 1 && str3 == "0")
                {
                    //最后一位（分）为0时，加上“整” 
                    str5 = str5 + '整';
                }
            }
            if (num == 0)
            {
                str5 = "零元整";
            }
            return str5;
        }


        /// <summary> 
        /// 转换人民币大小金额  (一个重载，将字符串先转换成数字在调用CmycurD)
        /// </summary> 
        /// <param name="num">用户输入的金额，字符串形式未转成decimal</param> 
        /// <returns></returns> 
        public static string StringToRMB(string numstr)
        {
            try
            {
                decimal num = Convert.ToDecimal(numstr);
                return NumToRMB(num);
            }
            catch
            {
                return "非数字形式！";
            }
        }
        #endregion 

        #region 全角半角转换
        /// <summary>
        /// 转全角的函数(SBC case)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string StringToSBC(string input)
        {
            //半角转全角：
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }

        /// <summary>
        ///  转半角的函数(DBC case)
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        public static string StringToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }
        #endregion 

        #region 转换为Int32类型
        /// <summary>
        /// 转换为Int32类型
        /// </summary>
        /// <param name="objNum"></param>
        /// <returns></returns>
        public static int ConvertToInt32(object objNum)
        {
            if (objNum == null)
            {
                return 0;
            }
            string strNum = objNum.ToString();
            if (IsNumeric(strNum))
            {

                if (strNum.ToString().Length > 9)
                {
                    if (strNum.StartsWith("-"))
                    {
                        return int.MinValue;
                    }
                    else
                    {
                        return int.MaxValue;
                    }
                }
                return Int32.Parse(strNum);
            }
            else
            {
                return 0;
            }
        }
        #endregion 


        #region html字符窜编码转换
        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(string str)
        {
            return HttpUtility.HtmlEncode(str);
        }

        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(string str)
        {
            return HttpUtility.HtmlDecode(str);
        }
        #endregion

        #region URL 字符串的编码结果
        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的解码结果结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }
        #endregion

      
        /// <summary>
        /// 判断是否emoji等4字节的Unicode字符
        /// </summary>
        /// <param name="codePoint"></param>
        /// <returns></returns>
        public static bool isNotEmojiCharacter(char codePoint)
        {
            if ((codePoint == 0x0) ||
                 (codePoint == 0x9) ||
                 (codePoint == 0xA) ||
                 (codePoint == 0xD) ||
                 ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                 ((codePoint >= 0xE000) && (codePoint <= 58300))|| 
                 ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)) 
                  )
                return true;
            else
                return false;
            
        }
        /// <summary>
        /// 获取非emoji等4字节的Unicode字符
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string GetNotEmojiStr(string source)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < source.Length; i++)
            {
                int j = 0;
                
                if (isNotEmojiCharacter(source[i]))
                    sb.Append(source[i]);

            }
            return sb.ToString();
        }


        #region string类型转换
        /// <summary>
        /// string型转换为bool型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的bool类型结果</returns>
        public static bool StringToBool(object Expression, bool defValue)
        {
            return TypeParse.StrToBool(Expression, defValue);
        }

        /// <summary>
        /// string型转换为Time型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的Time类型结果</returns>
        public static DateTime StringToDataTime(object Expression)
        {
            DateTime dt = new DateTime();
             DateTime.TryParse(Expression.ToString(),out dt);
             return dt;
        }

        /// <summary>
        /// 将对象转换为Int32类型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static int StringToInt(object Expression, int defValue)
        {
            return TypeParse.StrToInt(Expression, defValue);
        }

        /// <summary>
        /// string型转换为float型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static float StringToFloat(object strValue, float defValue)
        {
            return TypeParse.StrToFloat(strValue, defValue);
        }

        /// <summary>
        /// string型转换为decimal型
        /// </summary>
        /// <param name="strValue"></param>
        /// <param name="defValue"></param>
        /// <returns></returns>
        public static decimal StringToDecimal(string strValue, decimal defValue)
        {
            decimal de = new decimal();
            decimal.TryParse(strValue, out de);
            return de;
        }
        #endregion


        #region  字符窜转SHA256函数
        /// <summary>
        /// 字符窜转SHA256函数
        /// </summary>
        /// /// <param name="str">原始字符串</param>
        /// <returns>SHA256结果</returns>
        public static string StringToSHA256(string str)
        {
            byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
            SHA256Managed Sha256 = new SHA256Managed();
            byte[] Result = Sha256.ComputeHash(SHA256Data);
            SHA256Data = null;
            Sha256 = null;
            return Convert.ToBase64String(Result);  //返回长度为44字节的字符串
        }
        #endregion

        #region 简体中文和繁体中文互转
        /// <summary>
        /// 转换为简体中文
        /// </summary>
        public static string StringToSChinese(string str)
        {
            return Strings.StrConv(str, VbStrConv.SimplifiedChinese, 0);
        }

        /// <summary>
        /// 转换为繁体中文
        /// </summary>
        public static string StringToTChinese(string str)
        {
            return Strings.StrConv(str, VbStrConv.TraditionalChinese, 0);
        }

        #endregion

        #region 将全角数字转换为数字
        /// <summary>
        /// 将全角数字转换为数字
        /// </summary>
        /// <param name="SBCCase"></param>
        /// <returns></returns>
        public static string SBCCaseToNumberic(string SBCCase)
        {
            char[] c = SBCCase.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
                if (b.Length == 2)
                {
                    if (b[1] == 255)
                    {
                        b[0] = (byte)(b[0] + 32);
                        b[1] = 0;
                        c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
                    }
                }
            }
            return new string(c);
        }
        #endregion 

        #endregion


        #region +++文件/文件夹

         static  int GB = 1024 * 1024 * 1024;//定义GB的计算常量
          static  int MB = 1024 * 1024;//定义MB的计算常量
         static  int KB = 1024;//定义KB的计算常量
        /// <summary>
        /// 字节转换GBMBKB
        /// </summary>
        /// <param name="KSize"></param>
        /// <returns></returns>
        public static string ByteConversionGBMBKB(Int64 KSize)
        {
            if (KSize / GB >= 1)//如果当前Byte的值大于等于1GB
                return (Math.Round(KSize / (float)GB, 2)).ToString() + "GB";//将其转换成GB
            else if (KSize / MB >= 1)//如果当前Byte的值大于等于1MB
                return (Math.Round(KSize / (float)MB, 2)).ToString() + "MB";//将其转换成MB
            else if (KSize / KB >= 1)//如果当前Byte的值大于等于1KB
                return (Math.Round(KSize / (float)KB, 2)).ToString() + "KB";//将其转换成KGB
            else
                return KSize.ToString() + "Byte";//显示Byte值
        }


        #region "根据文件扩展名获取当前目录下的文件列表"
        /// <summary>
        /// 根据文件扩展名获取当前目录下的文件列表
        /// </summary>
        /// <param name="FileExt">文件扩展名</param>
        /// <returns>返回文件列表</returns>
        public static List<string> GetDirFileList(string path,string FileExt)
        {
            List<string> FilesList = new List<string>();
            string[] Files = Directory.GetFiles(path, string.Format("*.{0}", FileExt));
            foreach (string var in Files)
            {
                FilesList.Add(System.IO.Path.GetFileName(var).ToLower());
            }
            return FilesList;
        }
        #endregion
        /// <summary>
        /// 新建文档，如果文档时间大于指定时间则更新
        /// </summary>
        /// <param name="path"></param>
        /// <param name="content"></param>
        /// <param name="secend"></param>
        /// <returns></returns>
        public static bool FileIsOld(string path, Int32 secend)
        {
            FileInfo finfo = new FileInfo(path);
            if (finfo.Exists)
            {
                if (finfo.LastWriteTime.AddSeconds(secend) > DateTime.Now)
                {
                    return true;
                }

            }
            return false;

        }


        /// <summary>
        /// 去掉文件名中的无效字符,如 \ / : * ? " < > | 
        /// </summary>
        /// <param name="fileName">待处理的文件名</param>
        /// <returns>处理后的文件名</returns>
        public static  string ReplaceBadCharOfFileName(string fileName)
        {
            string str = fileName;
            str = str.Replace("\\", string.Empty);
            str = str.Replace("/", string.Empty);
            str = str.Replace(":", string.Empty);
            str = str.Replace("*", string.Empty);
            str = str.Replace("?", string.Empty);
            str = str.Replace("\"", string.Empty);
            str = str.Replace("<", string.Empty);
            str = str.Replace(">", string.Empty);
            str = str.Replace("|", string.Empty);
            str = str.Replace(" ", string.Empty);    //前面的替换会产生空格,最后将其一并替换掉
            return str;
        }

        /// <summary>
        ///返回文件内容.
        /// </summary>
        /// <param name="path">文件件物理路径</param>
        /// <returns>文件内容</returns>
        public static string GetFileContent(string path, Encoding encoding)
        {
            if (!File.Exists(path)) return "";
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            if (fs == null) throw new IOException("Unable to open the file: " + path);
            StreamReader sr = new StreamReader(fs, encoding);
            string res = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
            fs.Close();
            fs.Dispose();
            return res;
        }

        /// <summary>
        /// 生成文件
        /// </summary>
        /// <param name="pathAndName">文件路径和名称</param>
        /// <param name="content">写入内容</param>
        /// <param name="encoding">存储编码 为空则为：gb2312</param>
        /// <returns></returns>
        public static bool CreateFile(string pathAndName, string content, Encoding encoding)
        {
            FileStream fs = null;
            try
            {
                //指定日志文件的目录
                string fname = pathAndName;
                //定义文件信息对象
                FileInfo finfo = new FileInfo(fname);
                if (encoding == null)
                {
                    encoding = Encoding.GetEncoding("gb2312");
                }
                //判断文件是否存在
                if (!finfo.Exists)
                {
                    Directory.CreateDirectory(finfo.DirectoryName);

                }

                if (File.Exists(pathAndName))
                {
                    using (fs = new FileStream(pathAndName, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        Byte[] info = encoding.GetBytes(content);
                        fs.Write(info, 0, info.Length);
                        fs.Flush();
                        fs.Close();
                        info = null;
                    }
                }
                else
                {
                    using (fs = new FileStream(pathAndName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        Byte[] info = encoding.GetBytes(content);
                        fs.Write(info, 0, info.Length);
                        fs.Flush();
                        fs.Close();
                        info = null;
                    }
                }
            }
            catch (Exception ex)
            {

                AppLog.Write(string.Concat("写文件错误", ex.Message, "地址：", pathAndName), AppLog.LogMessageType.Error);
                return false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
            return true;
        }

        

        #region "根据文件扩展名获得文件的content-type"
        /// <summary>
        /// 根据文件扩展名获得文件的content-type
        /// </summary>
        /// <param name="fileextension">文件扩展名如.gif</param>
        /// <returns>文件对应的content-type 如:application/gif</returns>
        public static string GetFileMIME(string fileextension)
        {
            //set the default content-type
            const string DEFAULT_CONTENT_TYPE = "application/unknown";

            RegistryKey regkey, fileextkey;
            string filecontenttype;

            //the file extension to lookup


            try
            {
                //look in HKCR
                regkey = Registry.ClassesRoot;

                //look for extension
                fileextkey = regkey.OpenSubKey(fileextension);

                //retrieve Content Type value
                filecontenttype = fileextkey.GetValue("Content Type", DEFAULT_CONTENT_TYPE).ToString();

                //cleanup
                fileextkey = null;
                regkey = null;
            }
            catch
            {
                filecontenttype = DEFAULT_CONTENT_TYPE;
            }

            return filecontenttype;
        }
        #endregion

        #region "获得物理路径"
        /// <summary>
        /// 获得物理路径
        /// </summary>
        /// <param name="a">路径</param>
        /// <returns>物理路径</returns>
        public static string GetFullPath(string a)
        {
            string AppDir = System.AppDomain.CurrentDomain.BaseDirectory;
            if (a.IndexOf(":") < 0)
            {
                string str = a.Replace("..\\", "");
                if (str != a)
                {
                    int Num = (a.Length - str.Length) / ("..\\").Length + 1;
                    for (int i = 0; i < Num; i++)
                    {
                        AppDir = AppDir.Substring(0, AppDir.LastIndexOf("\\"));
                    }
                    str = "\\" + str;

                }
                a = AppDir + str;
            }
            return a;
        }
        #endregion

        #region  获得当前绝对路径
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (IsWeb())
            {
           
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    strPath = strPath.Substring(1, strPath.Length - 1);
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }
        

        #endregion

        #region 获取根目录
        /// <summary>
        /// 获取根目录  最后有\\
        /// </summary>
        /// <returns></returns>
        public static string GetServerPath()
        {
            if (IsWeb())
            {
                return HttpContext.Current.Request.PhysicalApplicationPath;
            }
            else
            {
                return  AppDomain.CurrentDomain.BaseDirectory.ToString();
            }
        }
        #endregion

        #region 判断文件名是否为浏览器可以直接显示的图片文件名
        /// <summary>
        /// 判断文件名是否为浏览器可以直接显示的图片文件名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否可以直接显示</returns>
        public static bool IsImgFilename(string filename)
        {
            filename = filename.Trim();
            if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
            {
                return false;
            }
            string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
            return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
        }
        #endregion

        #region 以指定的ContentType输出指定文件文件
        /// <summary>
        /// 以指定的ContentType输出指定文件文件
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="filename">输出的文件名</param>
        /// <param name="filetype">将文件输出时设置的ContentType</param>
        public static void ResponseFile(string filepath, string filename, string filetype)
        {
            Stream iStream = null;

            // 缓冲区为10k
            byte[] buffer = new Byte[10000];

            // 文件长度
            int length;

            // 需要读的数据长度
            long dataToRead;

            try
            {
                // 打开文件
                iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);


                // 需要读的数据长度
                dataToRead = iStream.Length;

                HttpContext.Current.Response.ContentType = filetype;
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Utils.UrlEncode(filename.Trim()).Replace("+", " "));

                while (dataToRead > 0)
                {
                    // 检查客户端是否还处于连接状态
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        length = iStream.Read(buffer, 0, 10000);
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        // 如果不再连接则跳出死循环
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    // 关闭文件
                    iStream.Close();
                }
            }
            HttpContext.Current.Response.End();
        }
        #endregion

        #region 判断文件流是否为UTF8字符集
        //0000 0000-0000 007F - 0xxxxxxx  (ascii converts to 1 octet!)
        //0000 0080-0000 07FF - 110xxxxx 10xxxxxx    ( 2 octet format)
        //0000 0800-0000 FFFF - 1110xxxx 10xxxxxx 10xxxxxx (3 octet format)

        /// <summary>
        /// 判断文件流是否为UTF8字符集
        /// </summary>
        /// <param name="sbInputStream">文件流</param>
        /// <returns>判断结果</returns>
        private static bool FileStreamIsUTF8(FileStream sbInputStream)
        {
            int i;
            byte cOctets;  // octets to go in this UTF-8 encoded character 
            byte chr;
            bool bAllAscii = true;
            long iLen = sbInputStream.Length;

            cOctets = 0;
            for (i = 0; i < iLen; i++)
            {
                chr = (byte)sbInputStream.ReadByte();

                if ((chr & 0x80) != 0) bAllAscii = false;

                if (cOctets == 0)
                {
                    if (chr >= 0x80)
                    {
                        do
                        {
                            chr <<= 1;
                            cOctets++;
                        }
                        while ((chr & 0x80) != 0);

                        cOctets--;
                        if (cOctets == 0) return false;
                    }
                }
                else
                {
                    if ((chr & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    cOctets--;
                }
            }

            if (cOctets > 0)
            {
                return false;
            }

            if (bAllAscii)
            {
                return false;
            }

            return true;

        }
        #endregion

        #region 返回指定目录下的非 UTF8 字符集文件
        /// <summary>
        /// 返回指定目录下的非 UTF8 字符集文件
        /// </summary>
        /// <param name="Path">路径</param>
        /// <returns>文件名的字符串数组</returns>
        public static string[] FindNoUTF8File(string Path)
        {
            //System.IO.StreamReader reader = null;
            StringBuilder filelist = new StringBuilder();
            DirectoryInfo Folder = new DirectoryInfo(Path);
            //System.IO.DirectoryInfo[] subFolders = Folder.GetDirectories(); 
            /*
            for (int i=0;i<subFolders.Length;i++) 
            { 
                FindNoUTF8File(subFolders[i].FullName); 
            }
            */
            FileInfo[] subFiles = Folder.GetFiles();
            for (int j = 0; j < subFiles.Length; j++)
            {
                if (subFiles[j].Extension.ToLower().Equals(".htm"))
                {
                    FileStream fs = new FileStream(subFiles[j].FullName, FileMode.Open, FileAccess.Read);
                    bool bUtf8 =Utils.FileStreamIsUTF8(fs);
                    fs.Close();
                    if (!bUtf8)
                    {
                        filelist.Append(subFiles[j].FullName);
                        filelist.Append("\r\n");
                    }
                    fs.Dispose();
                }
            }
            string[] strRetuns=Utils.SplitString(filelist.ToString(), "\r\n");
            subFiles = null;
            return strRetuns;

        }
        #endregion

        #region 建立文件夹
        /// <summary>
        /// 建立文件夹
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool CreateDir(string name)
        {
            if (!Directory.Exists(name))
            {
                return Utils.MakeSureDirectoryPathExists(name);

            }
            return true;
        }
        /// <summary>
        /// 返回文件内容
        /// </summary>
        /// <param name="filePathAndName"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string ReadFile(string filePathAndName, System.Text.Encoding encoding)
        {
            StreamReader sr = new StreamReader(filePathAndName, encoding);
            StringBuilder sb = new StringBuilder();
            while (!sr.EndOfStream)
            {
                sb.Append(sr.ReadLine());

            }
            sr.Close();
            sr.Dispose();
            return sb.ToString();
        }

        public static List<string> GetDirectoryFileNames(string dir, string suffix)
        {
            List<string> fileInfos = new List<string>();
            try
            {
                if (!Directory.Exists(dir))
                {
                    return fileInfos;
                }
                string[] files = Directory.GetFiles(dir);//得到文件
                foreach (string file in files)//循环文件
                {
                    string exname = file.Substring(file.LastIndexOf(".") + 1);//得到后缀名
                    // if (".txt|.aspx".IndexOf(file.Substring(file.LastIndexOf(".") + 1)) > -1)//查找.txt .aspx结尾的文件
                    if (suffix.IndexOf(exname) > -1)//如果后缀名为****文件
                    {
                        FileInfo fi = new FileInfo(file);//建立FileInfo对象
                        fileInfos.Add(fi.FullName);//把***文件全名加人到FileInfo对象
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(string.Concat("获取文件列表", e.Message));
            }
            return fileInfos;
        }
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="name">名称</param>
        /// <returns>创建是否成功</returns>
        [DllImport("dbgHelp", SetLastError = true)]
        private static extern bool MakeSureDirectoryPathExists(string name);
        #endregion

        #region 文件是否存在
        /// <summary>
        /// 返回文件是否存在
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否存在</returns>
        public static bool IsExistsFile(string filename)
        {
            return System.IO.File.Exists(filename);
        }
        #endregion

        #region 方法 -- 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filename"></param>
        public static void DeleteFile(string filePathAndName)
        {
            
            if (File.Exists(filePathAndName))
            {
                try
                {
                    File.Delete(filePathAndName);
                }
                catch(IOException e)
                {
                    throw e;
                }
            }
        }

        /// <summary>
        /// 遍历删除文件夹下文件和文件夹
        /// </summary>
        /// <param name="dir"></param>
        public static  void DeleteFolder(string dir)
        {
            if (Directory.Exists(dir)) //如果存在这个文件夹删除之 
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d))
                        File.Delete(d); //直接删除其中的文件 
                    else
                        DeleteFolder(d); //递归删除子文件夹 
                }
                Directory.Delete(dir); //删除已空文件夹 

            }

        }
        #endregion

        #region 备份文件

        /// <summary>
        /// 保存文本文件
        /// </summary>
        /// <param name="fileFullPathAndName">保存文件全路径</param>
        /// <param name="content">保存内容</param>
        /// <param name="encod">编码</param>
        /// <returns></returns>
        public static bool SaveFile(string fileFullPathAndName, string content, bool isAppend, System.Text.Encoding encoding)
        {

            StreamWriter w = new StreamWriter(fileFullPathAndName, isAppend, encoding);
            try
            {
                w.Write(content);
            }
            catch (Exception e)
            {
                throw e;
                return false;
            }
            finally
            {
                w.Flush();
                w.Close();
                w.Dispose();
            }
            return true;
        }
        /// <summary>
        /// 备份文件
        /// </summary>
        /// <param name="sourceFileName">源文件名</param>
        /// <param name="destFileName">目标文件名</param>
        /// <param name="overwrite">当目标文件存在时是否覆盖</param>
        /// <returns>操作是否成功</returns>
        public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite)
        {
            if (!System.IO.File.Exists(sourceFileName))
            {
                throw new FileNotFoundException(sourceFileName + "文件不存在！");
            }
            if (!overwrite && System.IO.File.Exists(destFileName))
            {
                return false;
            }
            try
            {
                System.IO.File.Copy(sourceFileName, destFileName, true);
                return true;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion 

        #region 备份文件
        /// <summary>
        /// 备份文件,当目标文件存在时覆盖
        /// </summary>
        /// <param name="sourceFileName">源文件名</param>
        /// <param name="destFileName">目标文件名</param>
        /// <returns>操作是否成功</returns>
        public static bool BackupFile(string sourceFileName, string destFileName)
        {
            return BackupFile(sourceFileName, destFileName, true);
        }
        #endregion 

        #region 回复文件
        /// <summary>
        /// 恢复文件
        /// </summary>
        /// <param name="backupFileName">备份文件名</param>
        /// <param name="targetFileName">要恢复的文件名</param>
        /// <param name="backupTargetFileName">要恢复文件再次备份的名称,如果为null,则不再备份恢复文件</param>
        /// <returns>操作是否成功</returns>
        public static bool RestoreFile(string backupFileName, string targetFileName, string backupTargetFileName)
        {
            try
            {
                if (!System.IO.File.Exists(backupFileName))
                {
                    throw new FileNotFoundException(backupFileName + "文件不存在！");
                }
                if (backupTargetFileName != null)
                {
                    if (!System.IO.File.Exists(targetFileName))
                    {
                        throw new FileNotFoundException(targetFileName + "文件不存在！无法备份此文件！");
                    }
                    else
                    {
                        System.IO.File.Copy(targetFileName, backupTargetFileName, true);
                    }
                }
                System.IO.File.Delete(targetFileName);
                System.IO.File.Copy(backupFileName, targetFileName);
            }
            catch (Exception e)
            {
                throw e;
            }
            return true;
        }

        /// <summary>
        /// 恢复文件
        /// </summary>
        /// <param name="backupFileName"></param>
        /// <param name="targetFileName"></param>
        /// <returns></returns>
        public static bool RestoreFile(string backupFileName, string targetFileName)
        {
            return RestoreFile(backupFileName, targetFileName, null);
        }
        #endregion 
        #endregion


        #region ++++html
        #region 生成指定数量的html空格符号
        /// <summary>
        /// 生成指定数量的html空格符号
        /// </summary>
        public static string GetSpaces(int nSpaces)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < nSpaces; i++)
            {
                sb.Append(" &nbsp;&nbsp;");
            }
            return sb.ToString();
        }
        #endregion

        #region html转换 去除
        /// <summary>
        /// 自定义转换成 HTML code
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>string</returns>
        public static string EncodeHtml(string str)
        {
            str = str.Replace("&", "&amp;");
            str = str.Replace("'", "''");
            str = str.Replace("\"", "&quot;");
            str = str.Replace(" ", "&nbsp;");
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace("\r\n", "<br />");
            str = str.Replace("\n", "<br />");
            str = str.Replace("\r", "<br />");
            str = str.Replace(",", "&def");
            str = str.Replace("'", "&dot");
            str = str.Replace(";", "&dec");
            return str;
        }
        /// <summary>
        ///自定义解析html成 普通文本
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>string</returns>
        public static string DecodeHtml(string str)
        {
            str = str.Replace("<br>", "\n");
            str = str.Replace("&gt;", ">");
            str = str.Replace("&lt;", "<");
            str = str.Replace("&nbsp;", " ");
            str = str.Replace("&quot;", "\"");

            return str;
        }
        #endregion 

        #region 转换为静态html
        /// <summary>
        /// 转换为静态html
        /// </summary>
        public void DynamicToHtml(string path, string outpath)
        {
            Page page = new Page();
            StringWriter writer = new StringWriter();
            page.Server.Execute(path, writer);
            FileStream fs;
            if (File.Exists(page.Server.MapPath("") + "\\" + outpath))
            {
                File.Delete(page.Server.MapPath("") + "\\" + outpath);
                fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
            }
            else
            {
                fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
            }
            byte[] bt = Encoding.Default.GetBytes(writer.ToString());
            fs.Write(bt, 0, bt.Length);
            fs.Close();
        }
        #endregion 

        #region 移除Html标记
        /// <summary>
        /// 移除Html标记
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveHtml(string content)
        {
            string regexstr = @"<[^>]*>";
            return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
        }
        #endregion

        #region 过滤HTML中的不安全标签
        /// <summary>
        /// 过滤HTML中的不安全标签
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveUnsafeHtml(string content)
        {
            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        }
        #endregion 

        #region 从HTML中获取文本,保留br,p,img
        /// <summary>
        /// 从HTML中获取文本,保留br,p,img
        /// </summary>
        /// <param name="HTML"></param>
        /// <returns></returns>
        public static string GetTextFromHTML(string HTML)
        {
            RegExpression.RegContext regcontext = new CMN.Common.RegExpression.RegContext(HTML, 'R', string.Empty);
            RegExpression.IRegExpression regex = new RegExpression.StringRegExpression(@"</?(?!br|/?p|img)[^>]*>");
            regex.Evaluate(regcontext);
            return regcontext.Context;
        }
        #endregion 

       
        #endregion

        #region +++++String

        #region 返回字符串真实长度
        /// <summary>
		/// 返回字符串真实长度, 1个汉字长度为2
		/// </summary>
		/// <returns></returns>
		public static int GetStringLength(string str)
		{
			return Encoding.Default.GetBytes(str).Length;
        }
        #endregion

        #region  是否包换字符串
        /// <summary>
        /// 是否包换字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="stringarray"></param>
        /// <param name="strsplit"></param>
        /// <returns></returns>
		public static bool IsCompriseString(string str, string stringarray, string strSplit)
		{
			if (stringarray == "" || stringarray == null)
			{
				return false;
			}
            bool rbool = false;
			str = str.ToLower();
			string[] stringArray = Utils.SplitString(stringarray.ToLower(), strSplit);
			for (int i = 0; i < stringArray.Length; i++)
			{
				//string t1 = str;
				//string t2 = stringArray[i];
				if(str.IndexOf(stringArray[i]) > -1)
				{
					rbool= true;
                    break;
				}
			}
            stringarray = null;
            return rbool;
			
        }
        #endregion

        #region "检测当前字符是否在以,号分开的字符串中(xx,sss,xaf,fdsf)"
        /// <summary>
        /// 检测当前字符是否在以,号分开的字符串中(xx,sss,xaf,fdsf)
        /// </summary>
        /// <param name="TempChar">需检测字符</param>
        /// <param name="TempStr">待检测字符串</param>
        /// <returns>存在true,不存在false</returns>
        public static bool CheckStrIsIn(string TempChar, string TempStr)
        {
            bool rBool = false;
            if (TempChar != null && TempStr != null)
            {
                string[] TempStrArray = TempStr.Split(',');
                for (int i = 0; i < TempStrArray.Length; i++)
                {
                    if (TempChar == TempStrArray[i].Trim())
                    {
                        rBool = true;
                        break;
                    }
                }
                TempStrArray = null;
            }
            return rBool;
        }
        #endregion

        #region 字符串数组转换成字符串
        /// <summary>
        ///  把字符串数组转换成字符串
        /// </summary>
        /// <param name="strList">字符串数组</param>
        /// <param name="connectStr">连接符号如，【9，9，0】</param>
        /// <param name="isEmpty">是否可以为空</param>
        /// <returns>转换成的字符串</returns>
        public static string ArrayToString(string[] strList,string connectStr,bool isEmpty)
        {
            string strReturn = string.Empty;
            for (int i = 0; i < strList.Length; i++)
            {
                if (isEmpty || !string.IsNullOrEmpty(strList[i]))  //空字符串是否连接
                {
                    if (i == 0)
                    {
                        strReturn = strList[i];
                    }
                    else
                    {
                        strReturn = string.Concat(strReturn, connectStr, strList[i]);
                    }
                }
            }
            return strReturn;
        }
        #endregion 

        #region 字符串是否在 Array数组中

        /// <summary>
        /// 判断指定字符串在指定字符串数组中的位置
        /// </summary>
        /// <param name="strSearch">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
        /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
        public static int GetInArrayID(string strSearch, string[] stringArray, bool caseInsensetive)
		{
			for (int i = 0; i < stringArray.Length; i++)
			{
				if (caseInsensetive)
				{
					if (strSearch.ToLower() == stringArray[i].ToLower())
					{
						return i;
					}
				}
				else
				{
					if (strSearch == stringArray[i])
					{
						return i;
					}
				}				
				
			}
			return -1;
        }

        
        /// <summary>
		/// 判断指定字符串在指定字符串数组中的位置
		/// </summary>
		/// <param name="strSearch">字符串</param>
		/// <param name="stringArray">字符串数组</param>
		/// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>		
		public static int GetInArrayID(string strSearch, string[] stringArray)
		{
			return GetInArrayID(strSearch, stringArray, true);
		}
		
		/// <summary>
		/// 判断指定字符串是否属于指定字符串数组中的一个元素
		/// </summary>
		/// <param name="strSearch">字符串</param>
		/// <param name="stringArray">字符串数组</param>
		/// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
		/// <returns>判断结果</returns>
		public static bool IsInArray(string strSearch, string[] stringArray, bool caseInsensetive)
		{
			return GetInArrayID(strSearch, stringArray, caseInsensetive) >= 0;
		}

		/// <summary>
		/// 判断指定字符串是否属于指定字符串数组中的一个元素
		/// </summary>
		/// <param name="str">字符串</param>
		/// <param name="stringarray">字符串数组</param>
		/// <returns>判断结果</returns>
		public static bool IsInArray(string str, string[] stringarray)
		{
			return IsInArray(str, stringarray, false);
		}

		/// <summary>
		/// 判断指定字符串是否属于指定字符串数组中的一个元素
		/// </summary>
		/// <param name="str">字符串</param>
		/// <param name="stringarray">内部以逗号分割单词的字符串</param>
		/// <returns>判断结果</returns>
		public static bool IsInArray(string str, string stringarray)
		{
			return IsInArray(str, SplitString(stringarray, ","), false);
		}

		/// <summary>
		/// 判断指定字符串是否属于指定字符串数组中的一个元素
		/// </summary>
		/// <param name="str">字符串</param>
		/// <param name="stringarray">内部以逗号分割单词的字符串</param>
		/// <param name="strsplit">分割字符串</param>
		/// <returns>判断结果</returns>
		public static bool IsInArray(string str, string stringarray, string strsplit)
		{
			return IsInArray(str, SplitString(stringarray, strsplit), false);
		}
		
		/// <summary>
		/// 判断指定字符串是否属于指定字符串数组中的一个元素
		/// </summary>
		/// <param name="str">字符串</param>
		/// <param name="stringarray">内部以逗号分割单词的字符串</param>
		/// <param name="strsplit">分割字符串</param>
		/// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
		/// <returns>判断结果</returns>
		public static bool IsInArray(string str, string stringarray, string strsplit, bool caseInsensetive)
		{
			return IsInArray(str, SplitString(stringarray, strsplit), caseInsensetive);
        }

        #endregion

        #region 删除字符串尾部的回车/换行/空格
        /// <summary>
		/// 删除字符串尾部的回车/换行/空格
		/// </summary>
		/// <param name="str"></param>
		/// <returns></returns>
		public static string ClearEnterBrSpace(string str)
		{
            RegExpression.RegContext regcontext = new CMN.Common.RegExpression.RegContext(str, 'R', string.Empty);
            RegExpression.IRegExpression regex = new RegExpression.StringRegExpression(@"(\r\n )");
            regex.Evaluate(regcontext);
            return regcontext.Context;
		}




		/// <summary>
		/// 清除给定字符串中的回车及换行符
		/// </summary>
		/// <param name="str">要清除的字符串</param>
		/// <returns>清除后返回的字符串</returns>
        public static string ClearEnterBr(string str)
		{
		    RegExpression.RegContext regcontext=new CMN.Common.RegExpression.RegContext(str,'R',string.Empty);
            RegExpression.IRegExpression regex=new RegExpression.StringRegExpression(@"(\r\n)");
            regex.Evaluate(regcontext);
            return regcontext.Context;

        }
        #endregion

        #region 截取指定长度的子字符串
        /// <summary>
		/// 从字符串的指定位置截取指定长度的子字符串
		/// </summary>
		/// <param name="str">原字符串</param>
		/// <param name="startIndex">子字符串的起始位置</param>
		/// <param name="length">子字符串的长度</param>
		/// <returns>子字符串</returns>
		public static string CutString(string str,int startIndex,int length)
		{
			if (startIndex >= 0)
			{
				if (length < 0)
				{
					length = length * -1;
					if (startIndex - length < 0)
					{
						length = startIndex;
						startIndex = 0;
					}
					else
					{
						startIndex = startIndex - length;
					}
				}


				if (startIndex > str.Length)
				{
					return "";
				}


			}
			else
			{
				if (length < 0)
				{
					return "";
				}
				else
				{
					if (length + startIndex > 0)
					{
						length = length + startIndex;
						startIndex = 0;
					}
					else
					{
						return "";
					}
				}
			}

			if (str.Length - startIndex < length)
			{
				length = str.Length - startIndex;
			}

			return str.Substring(startIndex,length);
		}

        /// <summary>
        /// 从字符串的指定位置开始截取到字符串结尾的了符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <returns>子字符串</returns>
        public static string CutString(string str, int startIndex)
        {
            return CutString(str, startIndex, str.Length);
        }
        #endregion

        #region 返回指定长度的字符串,区分汉字的
        /// <summary>
        /// 返回指定长度的字符串,区分汉字的
        /// </summary>
        /// <param name="str">要测试的字符串</param>
        /// <param name="length">返回长度</param>
        /// <param name="isShowEllipsis">是否加省略号</param>
        /// <returns></returns>
        public static string GetLengthString(string str, int returnLength, bool isShowEllipsis)
        {

            if (!string.IsNullOrEmpty(str))
            {
                if (GetStringLength(str) > returnLength)
                {
                    int str_length = str.Length;

                    int len = 0;

                    for (int i = 0; i < str_length; i++)
                    {
                        byte[] byte_len = Encoding.Default.GetBytes(str.Substring(i, 1));
                        if (byte_len.Length > 1)
                            len += 2;  //如果长度大于1，是中文，占两个字节，+2
                        else
                            len += 1;  //如果长度等于1，是英文，占一个字节，+1

                        if (len >= returnLength)
                        {
                            if (isShowEllipsis)
                                return string.Concat(str.Substring(0, i - 1), "…");
                            else
                                return str.Substring(0, i - 1);
                        }
                    }
                    return "";
                }
                else
                {
                    return str;
                }

            }
            else
            {
                return "";
            }

        }
        #endregion

        #region 取指定长度的字符串(超出的部分用指定字符串代替)
        /// <summary>
        /// 取指定长度的字符串(超出的部分用指定字符串代替)
		/// </summary>
		/// <param name="p_SrcString">要检查的字符串</param>
		/// <param name="p_Length">指定长度</param>
		/// <param name="p_TailString">用于替换的字符串</param>
		/// <returns>截取后的字符串</returns>
		public static string GetSubString(string p_SrcString, int p_Length, string p_TailString) 
		{
            return GetSubString(p_SrcString, 0, p_Length, p_TailString);
		}
        /// <summary>
        /// 获取自定长度的字符窜，不够按指定字符补气
        /// </summary>
        /// <param name="strSrc">需检测的字符串</param>
        /// <param name="cFill">要补齐的字符</param>
        /// <param name="retrunLength">最大长度</param>
        /// <param name="fillDirection">true为字符串前补齐，false为后</param>
        /// <returns></returns>
        public static string GetFillString(string strSrc, string cFill, int returnLength, bool fillDirection)
        {
            if (strSrc.Length < returnLength)
            {
                string strTemp = string.Empty;
                for (int i = 0; i < returnLength - strSrc.Length; i++)
                {

                    strTemp = string.Concat(cFill, strTemp);

                }
                if (fillDirection)
                {
                    strSrc = string.Concat(strTemp, strSrc);
                }
                else
                {
                    strSrc = string.Concat(strSrc, strTemp);
                }
                strTemp = null;
            }
            return strSrc;
        }
            
        
        
        #region 字符串截取补字符函数
        /// <summary>
        /// 字符串截取补字符函数
        /// </summary>
        /// <param name="s">要处理的字符串</param>
        /// <param name="len">长度</param>
        /// <param name="b">补充的字符</param>
        /// <returns>处理后字符</returns>
        public static string GetSubStringLen(string s, int len, char b)
        {
            if (string.IsNullOrEmpty(s))
                return "";
            if (s.Length >= len)
                return s.Substring(0, len);
            return s.PadRight(len, b);
        }
        #endregion

        /// <summary>
        /// 取指定长度的字符串(超出的部分用指定字符串代替)
        /// </summary>
        /// <param name="p_SrcString">要检查的字符串</param>
        /// <param name="p_StartIndex">起始位置</param>
        /// <param name="p_Length">指定长度</param>
        /// <param name="p_TailString">用于替换的字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
        {
            string myResult = p_SrcString;
            try
            {
               

                if (p_Length >= 0)
                {
                   // byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);

                    //当字符串长度大于起始位置
                    if (p_SrcString.Length > p_StartIndex)
                    {
                        int p_EndIndex = p_SrcString.Length;

                        //当要截取的长度在字符串的有效长度范围内
                        if (p_SrcString.Length < (p_StartIndex + p_Length))
                        {
                            
                            p_Length = p_SrcString.Length - p_StartIndex;
                            p_TailString = "";
                        }

                        myResult = p_SrcString.Substring(p_StartIndex, p_Length);
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.Write(ex.Message + p_SrcString + ":" + p_StartIndex.ToString() + p_Length.ToString(), AppLog.LogMessageType.Debug, ex);
            }

            return myResult;
        }
        #endregion

        #region 自定义的替换字符串函数
        /// <summary>
        /// 自定义的替换字符串函数
        /// </summary>
        /// <param name="SourceString">原字符串</param>
        /// <param name="SearchString">要替换的字符串</param>
        /// <param name="ReplaceString">替换成的字符串</param>
        /// <param name="IsCaseInsensetive">是否区分大小写</param>
        /// <returns></returns>
		public static string ReplaceString(string SourceString, string SearchString,string ReplaceString, bool IsCaseInsensetive)
		{
			return Regex.Replace(SourceString, SearchString, ReplaceString, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None);
        }

        /// <summary>
        /// 自定义的批量替换字符串函数
        /// </summary>
        /// <param name="SourceString">原字符串</param>
        /// <param name="SearchString">要替换的字符串</param>
        /// <param name="ReplaceString">替换成的字符串</param>
        /// <param name="strSplit">分隔符</param>
        /// <param name="IsCaseInsensetive">是否区分大小写</param>
        /// <returns></returns>
        public static string ReplaceArray(string SourceString, string SearchString, string ReplaceString, string strSplit, bool IsCaseInsensetive)
        {
            string[] searchs = SearchString.Split(new string[] { strSplit }, StringSplitOptions.RemoveEmptyEntries);
            string[] replaces = ReplaceString.Split(new string[] { strSplit }, StringSplitOptions.RemoveEmptyEntries);
            if (searchs.Length != replaces.Length)
            {
                searchs = null;
                replaces = null;
                throw new Exception("批量替换，替换和被替换数组长度不相等");
                return "";
            }
            for (int i = 0; i < searchs.Length; i++)
            {
                SourceString = Regex.Replace(SourceString, Regex.Escape(searchs[i].ToString()),replaces[i].ToString(), IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None);
            }
            searchs = null;
            replaces = null;
            return SourceString;
        }

        /// <summary>
        /// 自定义的批量替换为空函数
        /// </summary>
        /// <param name="SourceString">原字符串</param>
        /// <param name="SearchString">要替换的字符串</param>
        /// <param name="strSplit">分隔符</param>
        /// <param name="IsCaseInsensetive">是否区分大小写</param>
        /// <returns></returns>
        public static string ReplaceArrayToEmpty(string SourceString, string SearchString, string strSplit, bool IsCaseInsensetive)
        {
            if (!string.IsNullOrEmpty(SearchString))
            {
                string[] searchs = SearchString.Split(new string[] { strSplit }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < searchs.Length; i++)
                {
                    SourceString = Regex.Replace(SourceString, Regex.Escape(searchs[i].ToString()), string.Empty, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None);
                }
                searchs = null;
            }
            return SourceString;
        }
        #endregion

        #region 分割字符串
        /// <summary>
		/// 分割字符串
		/// </summary>
		public static string[] SplitString(string strContent, string strSplit)
		{
			if(strContent.IndexOf(strSplit) < 0)
			{
				string[] tmp = {strContent};
				return tmp;
			}
			return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
		}

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <returns></returns>
        public static string[] SplitString(string strContent, string strSplit, int p_3)
        {
            string[] result = new string[p_3];

            string[] splited = SplitString(strContent,strSplit);

            for (int i = 0; i < p_3; i++)
            {
                if (i < splited.Length)
                    result[i] = splited[i];
                else
                    result[i] = string.Empty;
            }
            splited = null;
            return result;
        }
        #endregion 

        #region 格式化字节数字符串
        /// <summary>
		/// 格式化字节数字符串
		/// </summary>
		/// <param name="bytes"></param>
		/// <returns></returns>
		public static string FormatBytesStr(int bytes)
		{
			if (bytes > 1073741824)
			{
				return ((double)(bytes / 1073741824)).ToString("0") + "G";
			}
			if (bytes > 1048576)
			{
				return ((double)(bytes / 1048576)).ToString("0") + "M";
			}
			if (bytes > 1024)
			{
				return ((double)(bytes / 1024)).ToString("0") + "K";
			}
			return bytes.ToString() + "Bytes";
        }
        #endregion

        #region 字符串和字符串数组转换
        /// <summary>
        /// 字符串转换成字符串数组
        /// </summary>
        /// <param name="str"></param>
        /// <param name="speater"></param>
        /// <param name="toLower"></param>
        /// <returns></returns>
        public static List<string> StringToArray(string str, char speater, bool toLower)
        {
            List<string> list = new List<string>();
            string[] ss = str.Split(speater);
            foreach (string s in ss)
            {
                if (!string.IsNullOrEmpty(s) && s != speater.ToString())
                {
                    string strVal = s;
                    if (toLower)
                    {
                        strVal = s.ToLower();
                    }
                    list.Add(strVal);
                }
            }
            ss = null;
            return list;
        }
       /// <summary>
       /// 字符串数组转换成字符窜
       /// </summary>
       /// <param name="list"></param>
       /// <param name="speater"></param>
       /// <returns></returns>
        public static string ArrayotString(List<string> list, string speater)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == list.Count - 1)
                {
                    sb.Append(list[i]);
                }
                else
                {
                    sb.Append(list[i]);
                    sb.Append(speater);
                }
            }
            return sb.ToString();
        }
        #endregion 

        #region 字符串数组是不是都为数字型
        /// <summary>
        /// 判断给定的字符串数组(strNumber)中的数据是不是都为数值型
        /// </summary>
        /// <param name="strNumber">要确认的字符串数组</param>
        /// <returns>是则返加true 不是则返回 false</returns>
        public static bool IsNumericArray(string[] strNumber)
        {
            return TypeParse.IsNumericArray(strNumber);
        }
        #endregion 
       
        #region 删除最后一个字符
        /// <summary>
        /// 删除最后一个字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ClearLastChar(string str)
        {
            if (str == "")
                return "";
            else
                return str.Substring(0, str.Length - 1);
        }
        #endregion

        #region 将字符串转换为Color
        /// <summary>
        /// 将字符串转换为Color
        /// </summary>
        /// <param name="color"></param>
        /// <returns></returns>
        public static Color StringToColor(string color)
        {
            int red, green, blue = 0;
            char[] rgb;
            Color rcolor ;
            color = color.TrimStart('#');
            color = Regex.Replace(color.ToLower(), "[g-zG-Z]", "");
            switch (color.Length)
            { 
                case 3:
                    rgb = color.ToCharArray();
                    red = Convert.ToInt32(rgb[0].ToString() + rgb[0].ToString(), 16);
                    green = Convert.ToInt32(rgb[1].ToString() + rgb[1].ToString(), 16);
                    blue = Convert.ToInt32(rgb[2].ToString() + rgb[2].ToString(), 16);
                   rcolor= Color.FromArgb(red, green, blue);
                   break;
                case 6:
                    rgb = color.ToCharArray();
                    red = Convert.ToInt32(rgb[0].ToString() + rgb[1].ToString(), 16);
                    green = Convert.ToInt32(rgb[2].ToString() + rgb[3].ToString(), 16);
                    blue = Convert.ToInt32(rgb[4].ToString() + rgb[5].ToString(), 16);
                    rcolor= Color.FromArgb(red, green, blue);
                    break;
                default:
                    rcolor= Color.FromName(color);
                    break;

            }
            rgb = null;
            return rcolor;
        }
        #endregion

        #region  将列表转换成字符串
        /// <summary>
        /// 将列表转换成字符串
        /// </summary>
        /// <param name="lst">要转换的list</param>
        /// <param name="strSplit">分割符</param>
        /// <param name="maxLengh">lst的最大索引,0则不判断</param>
        /// <returns>string</returns>
        public static string ListToString(List<string> lst, string strSplit, Int32 maxLengh)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < lst.Count; i++)
            {
                if (i != lst.Count - 1)
                {
                    if (maxLengh == 0)
                    {
                        sb.Append(string.Concat(lst[i].ToString(), strSplit));
                    }
                    else
                    {
                        if (i < maxLengh)
                        {
                            sb.Append(string.Concat(lst[i].ToString(), strSplit));
                        }
                        else
                        {
                            sb.Append(lst[i].ToString());
                            break;
                        }
                    }
                }
                else
                {
                    sb.Append(lst[i].ToString());
                }
            }
            return sb.ToString();
        }
        #endregion

        #endregion

        #region ++++dataTime

        #region 时间差值
        /// <summary>
        /// 返回相差的秒数
        /// </summary>
        /// <param name="Time"></param>
        /// <param name="Sec"></param>
        /// <returns></returns>
        public static int StringDateDiffSeconds(string Time, int Sec)
        {
            TimeSpan ts = DateTime.Now - DateTime.Parse(Time).AddSeconds(Sec);
            if (ts.TotalSeconds > int.MaxValue)
            {
                return int.MaxValue;
            }
            else if (ts.TotalSeconds < int.MinValue)
            {
                return int.MinValue;
            }
            return (int)ts.TotalSeconds;
        }




        /// <summary>
        /// 返回相差的分钟数
        /// </summary>
        /// <param name="time"></param>
        /// <param name="minutes"></param>
        /// <returns></returns>
        public static int StringDateDiffMinutes(string time, int minutes)
        {
            if (time == "" || time == null)
                return 1;
            TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes);
            if (ts.TotalMinutes > int.MaxValue)
            {
                return int.MaxValue;
            }
            else if (ts.TotalMinutes < int.MinValue)
            {
                return int.MinValue;
            }
            return (int)ts.TotalMinutes;
        }

        /// <summary>
        /// 返回相差的小时数
        /// </summary>
        /// <param name="time"></param>
        /// <param name="hours"></param>
        /// <returns></returns>
        public static int StringDateDiffHours(string time, int hours)
        {
            if (time == "" || time == null)
                return 1;
            TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours);
            if (ts.TotalHours > int.MaxValue)
            {
                return int.MaxValue;
            }
            else if (ts.TotalHours < int.MinValue)
            {
                return int.MinValue;
            }
            return (int)ts.TotalHours;
        }
        #endregion

        #region 返回当前时间增加(分钟)后的字符串
        /// <summary>
        /// 返回当前时间增加(分钟)后的字符串
        /// </summary>
        /// <param name="minutes"></param>
        /// <returns></returns>
        public static string AddMinutes(int minutes)
        {
            string newtime = (DateTime.Now).AddMinutes(minutes).ToString();
            return newtime;

        }
        #endregion

        #region 把秒转换成分钟
        /// <summary>
        /// 把秒转换成分钟
        /// </summary>
        /// <returns></returns>
        public static int SecondToMinute(int Second)
        {
            decimal mm = (decimal)((decimal)Second / (decimal)60);
            return Convert.ToInt32(Math.Ceiling(mm));
        }
        #endregion

        #region 返回某年某月最后一天
        /// <summary>
        /// 返回某年某月最后一天
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="month">月份</param>
        /// <returns>日</returns>
        public static int GetMonthLastDate(int year, int month)
        {
            DateTime lastDay = new DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month));
            int Day = lastDay.Day;
            return Day;
        }
        #endregion
        
        #region 返回时间差
        public static string DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            string dateDiff = null;
            try
            {
                //TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                //TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                //TimeSpan ts = ts1.Subtract(ts2).Duration();
                TimeSpan ts = DateTime2 - DateTime1;
                if (ts.Days >= 1)
                {
                    dateDiff = DateTime1.Month.ToString() + "月" + DateTime1.Day.ToString() + "日";
                }
                else
                {
                    if (ts.Hours > 1)
                    {
                        dateDiff = ts.Hours.ToString() + "小时前";
                    }
                    else
                    {
                        dateDiff = ts.Minutes.ToString() + "分钟前";
                    }
                }
            }
            catch
            { }
            return dateDiff;
        }
        #endregion

        #region 日期转换
        /// <summary>
        /// 日期转换
        /// </summary>
        /// <param name="DateStr">需要转换的日期</param>
        /// <param name="DateModel">要转换成的格式[1:yyyy-mm-dd]</param>
        /// <returns></returns>
        public static string DateTransform(DateTime DateStr, string DateModel)
        {
            string restr = "";
            if (DateStr.ToString() != string.Empty)
                switch (DateModel)
                {
                    case "yyyy/MM/dd":
                        restr = DateStr.ToString("yyyy/MM/dd", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM/dd/yyyy":
                        restr = DateStr.ToString("MM/dd/yyyy", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "yyyy-MM-dd":
                        restr = DateStr.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM-dd-yyyy":
                        restr = DateStr.ToString("MM-dd-yyyy", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "yyyy.MM.dd":
                        restr = DateStr.ToString("yyyy.MM.dd", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM.dd.yyyy":
                        restr = DateStr.ToString("MM.dd.yyyy", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "yyyy年MM月dd日":
                        restr = DateStr.ToString("yyyy年MM月dd日", DateTimeFormatInfo.InvariantInfo);
                        break;
                    case "MM月dd日yyyy年":
                        restr = DateStr.ToString("MM月dd日yyyy年", DateTimeFormatInfo.InvariantInfo);
                        break;
                    default:
                        restr = DateStr.ToShortDateString();
                        break;
                }
            return restr;
        }

        #endregion

        #region 返回时间
        /// <summary>
        /// 返回标准时间格式string
        /// </summary>
        public static string GetTime()
        {
            return DateTime.Now.ToString("HH:mm:ss");
        }

        /// <summary>
        /// 返回标准时间格式string
        /// </summary>
        public static string GetDateTime()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 返回相对于当前时间的相对天数
        /// </summary>
        public static string GetDateTime(int relativeday)
        {
            return DateTime.Now.AddDays(relativeday).ToString("yyyy-MM-dd HH:mm:ss");
        }

        /// <summary>
        /// 返回标准时间格式string
        /// </summary>
        public static string GetDateTimeF()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
        }
        #endregion

        #region 时间差值
        /// <summary>
        /// 返回相差的秒数
        /// </summary>
        /// <param name="Time"></param>
        /// <param name="Sec"></param>
        /// <returns></returns>
        public static int StrDateDiffSeconds(string Time, int Sec)
        {
            TimeSpan ts = DateTime.Now - DateTime.Parse(Time).AddSeconds(Sec);
            if (ts.TotalSeconds > int.MaxValue)
            {
                return int.MaxValue;
            }
            else if (ts.TotalSeconds < int.MinValue)
            {
                return int.MinValue;
            }
            return (int)ts.TotalSeconds;
        }

        /// <summary>
        /// 返回相差的分钟数
        /// </summary>
        /// <param name="time"></param>
        /// <param name="minutes"></param>
        /// <returns></returns>
        public static int StrDateDiffMinutes(string time, int minutes)
        {
            if (time == "" || time == null)
                return 1;
            TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes);
            if (ts.TotalMinutes > int.MaxValue)
            {
                return int.MaxValue;
            }
            else if (ts.TotalMinutes < int.MinValue)
            {
                return int.MinValue;
            }
            return (int)ts.TotalMinutes;
        }

        /// <summary>
        /// 返回相差的小时数
        /// </summary>
        /// <param name="time"></param>
        /// <param name="hours"></param>
        /// <returns></returns>
        public static int StrDateDiffHours(string time, int hours)
        {
            if (time == "" || time == null)
                return 1;
            TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours);
            if (ts.TotalHours > int.MaxValue)
            {
                return int.MaxValue;
            }
            else if (ts.TotalHours < int.MinValue)
            {
                return int.MinValue;
            }
            return (int)ts.TotalHours;
        }
        #endregion 

        #region Unix时间字符串
        /// <summary>
        /// 返回Unix时间字符串
        /// </summary>
        /// <returns></returns>
        public static string GetUnixTime()
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = DateTime.Parse(DateTime.Now.ToString());
            TimeSpan toNow = dtNow.Subtract(dtStart);

            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
            return timeStamp;
        }
        /// <summary>
        /// 将Unix时间转换成Datetime
        /// </summary>
        /// <param name="strUnixTime"></param>
        /// <returns></returns>
        public static DateTime UnixStringToDateTime(string strUnixTime)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(strUnixTime + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }
        #endregion
        #endregion





    } 
}
